Repository: rib/gputop Branch: master Commit: 01d2fd4fad3e Files: 167 Total size: 13.0 MB Directory structure: gitextract_e5ud6w3z/ ├── .gitignore ├── .travis.yml ├── README.md ├── data/ │ ├── .gitignore │ ├── Makefile.xml │ ├── README.md │ ├── gputop.proto │ ├── guids.xml │ ├── oa-bdw.xml │ ├── oa-bxt.xml │ ├── oa-cflgt2.xml │ ├── oa-cflgt3.xml │ ├── oa-chv.xml │ ├── oa-cnl.xml │ ├── oa-glk.xml │ ├── oa-hsw.xml │ ├── oa-icl.xml │ ├── oa-kblgt2.xml │ ├── oa-kblgt3.xml │ ├── oa-lkf.xml │ ├── oa-sklgt2.xml │ ├── oa-sklgt3.xml │ ├── oa-sklgt4.xml │ └── oa-tgl.xml ├── docker/ │ ├── travis-build-environment-centos/ │ │ ├── Dockerfile │ │ ├── README.md │ │ └── build-travis-docker-image.sh │ └── travis-build-environment-ubuntu/ │ ├── Dockerfile │ ├── README.md │ └── build-travis-docker-image.sh ├── gputop.doap ├── lib/ │ ├── gputop-client-context.c │ ├── gputop-client-context.h │ ├── gputop-log.h │ ├── gputop-network.h │ ├── gputop-oa-counters.c │ ├── gputop-oa-counters.h │ ├── gputop-oa-metrics.c │ ├── gputop-oa-metrics.h │ ├── gputop-util.h │ ├── meson.build │ └── tracepoint_format.leg ├── mesa/ │ ├── include/ │ │ ├── c11/ │ │ │ ├── threads.h │ │ │ ├── threads_posix.h │ │ │ └── threads_win32.h │ │ ├── c99_alloca.h │ │ ├── c99_compat.h │ │ ├── c99_math.h │ │ ├── drm-uapi/ │ │ │ ├── README │ │ │ ├── drm.h │ │ │ ├── drm_fourcc.h │ │ │ ├── drm_mode.h │ │ │ ├── i915_drm.h │ │ │ └── vc4_drm.h │ │ ├── no_extern_c.h │ │ └── pci_ids/ │ │ ├── i965_pci_ids.h │ │ └── iris_pci_ids.h │ ├── meson.build │ └── src/ │ ├── compiler/ │ │ └── shader_enums.h │ ├── intel/ │ │ ├── common/ │ │ │ └── gen_gem.h │ │ └── dev/ │ │ ├── gen_device_info.c │ │ └── gen_device_info.h │ ├── mesa/ │ │ └── main/ │ │ ├── compiler.h │ │ └── hash.h │ └── util/ │ ├── bitscan.c │ ├── bitscan.h │ ├── bitset.h │ ├── hash_table.c │ ├── hash_table.h │ ├── list.h │ ├── macros.h │ ├── ralloc.c │ └── ralloc.h ├── meson.build ├── meson_options.txt ├── scripts/ │ ├── deploy-demo-site.sh │ ├── gen-template.py │ ├── gputop-oa-codegen.py │ ├── i915-perf-kernelgen.py │ ├── mdapi-xml-convert.py │ ├── meson-cross/ │ │ ├── emscripten-docker-debug.txt │ │ └── emscripten-docker-release.txt │ ├── pylibs/ │ │ ├── .gitignore │ │ ├── __init__.py │ │ ├── codegen/ │ │ │ └── __init__.py │ │ └── oa_guid_registry/ │ │ └── __init__.py │ ├── travis-ci-build.sh │ ├── travis-ci-prep-docker-centos.sh │ ├── travis-ci-prep-docker-ubuntu.sh │ ├── travis-ci-test.sh │ └── update-guids.py ├── server/ │ ├── gputop-cpu.c │ ├── gputop-cpu.h │ ├── gputop-debugfs.c │ ├── gputop-debugfs.h │ ├── gputop-gl.c │ ├── gputop-gl.h │ ├── gputop-ioctl.c │ ├── gputop-log.c │ ├── gputop-main.c │ ├── gputop-mainloop.h │ ├── gputop-ncurses.c │ ├── gputop-perf.c │ ├── gputop-perf.h │ ├── gputop-server.c │ ├── gputop-server.h │ ├── gputop-string.c │ ├── gputop-string.h │ ├── gputop-system.c │ ├── gputop-sysutil.c │ ├── gputop-sysutil.h │ ├── meson.build │ ├── registry/ │ │ ├── .gitignore │ │ ├── egl.xml │ │ ├── genapis.py │ │ ├── gl.xml │ │ ├── glx.xml │ │ └── reg.py │ └── stdatomic.h ├── subprojects/ │ ├── .gitignore │ ├── h2o.wrap │ ├── libuv.wrap │ ├── packagecache/ │ │ └── .gitignore │ ├── peg.wrap │ ├── protobuf-c.wrap │ ├── protobuf.wrap │ └── wslay.wrap ├── ui/ │ ├── gputop-emscripten-network.c │ ├── gputop-soup-network.c │ ├── gputop-ui-main.cpp │ ├── gputop-ui-multilines.cpp │ ├── gputop-ui-multilines.h │ ├── gputop-ui-piechart.cpp │ ├── gputop-ui-piechart.h │ ├── gputop-ui-plots.cpp │ ├── gputop-ui-plots.h │ ├── gputop-ui-timeline.cpp │ ├── gputop-ui-timeline.h │ ├── gputop-ui-topology.cpp │ ├── gputop-ui-topology.h │ ├── gputop-ui-utils.cpp │ ├── gputop-ui-utils.h │ ├── gputop-ui.css │ ├── gputop-uv-network.c │ ├── imgui/ │ │ ├── LICENSE.txt │ │ ├── imconfig.h │ │ ├── imgui.cpp │ │ ├── imgui.h │ │ ├── imgui_demo.cpp │ │ ├── imgui_draw.cpp │ │ ├── imgui_impl_glfw_gl3.cpp │ │ ├── imgui_impl_glfw_gl3.h │ │ ├── imgui_impl_gtk3_cogl.cpp │ │ ├── imgui_impl_gtk3_cogl.h │ │ ├── imgui_impl_sdl_gles2.cpp │ │ ├── imgui_impl_sdl_gles2.h │ │ ├── imgui_internal.h │ │ ├── stb_rect_pack.h │ │ ├── stb_textedit.h │ │ └── stb_truetype.h │ ├── index.html │ └── meson.build ├── utils/ │ ├── gputop-configs.c │ └── meson.build └── wrapper/ ├── gputop-uv-network.c ├── gputop-wrapper-main.c └── meson.build ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ build **.dir-locals.el ================================================ FILE: .travis.yml ================================================ sudo: required services: - docker language: c os: - linux compiler: - gcc env: global: # GH_TOKEN scope=public_repo, for pushing to gh-pages demo site, # limited to builds of the rib/gputop repo - secure: "CXTLgHD8PYC3OQO88QHFaCu6tfF4Pp/fHvn9cguOptBUrkOad5IKq43r4wNv+VFKl9f99K4tvBThHOLAryi+2OFDwkKIiIHfhyaEewLQKFOxGlXLQf6JlKslzVU8/r5BeKt1KH1fuNmaqGqyv39snVmBE0HGmHntpY8U0CtISwL8riS8fQWT/Ae3vUVDnkCaHen6QfCvOQtwZey7GwFp2+Dn7lVC4xviOTR2zEydMzRnvhzwO4NkeCtigqgY5jEW6Irmk72Ng/27UTYY/ps+/dvtLeL2xGWziPRWf92z6qMGJAuX6CfAkwPHF4G/MNnOSQ2R3YZPDPzSLitpz/ThXnpfUlJMpa7fV/RZMp9+WjbSvyfi4mUG+fyvWPS3oXkF05U5rmZn5LHrTvjFUXt7lj3n/Ugkk2+1dTFxwHE1HzV85C1kNgOIgwhJLvfddyhUncwBHKMUs6q5w9sha+5zMF0YTttG8EJFwHKqjCdwycJ5g1/i0mmj6qzTFosUmH0N+3bIPAO/ca6DjUXzoH1f0BeL22M3Uy3CEeWgfn7X87fRGK8pgHE6d3VYb6VdO8ys17Cz3SkRn4S71VwXqZg6nl462C/nUR23Rpi/ijYWhPYAqXVGPUsCOAzUl1PTBMDsHqWk2hUto2WEXCnVhpBoq5FkJ0RhV03tPyAZCtoCNcw=" matrix: - CONFIG_OPTS="--buildtype=debug" PREP_SCRIPT="scripts/travis-ci-prep-docker-ubuntu.sh" BASE_IMAGE="djdeath/gputop-travis-ci-ubuntu16.04-18.01.09" - CONFIG_OPTS="--buildtype=release" PREP_SCRIPT="scripts/travis-ci-prep-docker-ubuntu.sh" BASE_IMAGE="djdeath/gputop-travis-ci-ubuntu16.04-18.01.09" - CONFIG_OPTS="--buildtype=debug -Dnative_ui=true" PREP_SCRIPT="scripts/travis-ci-prep-docker-ubuntu.sh" BASE_IMAGE="djdeath/gputop-travis-ci-ubuntu16.04-18.01.09" - CONFIG_OPTS="--buildtype=release -Dnative_ui=true" PREP_SCRIPT="scripts/travis-ci-prep-docker-ubuntu.sh" BASE_IMAGE="djdeath/gputop-travis-ci-ubuntu16.04-18.01.09" - CONFIG_OPTS="--buildtype=debug --cross=scripts/meson-cross/emscripten-docker-debug.txt -Dwebui=true" PREP_SCRIPT="scripts/travis-ci-prep-docker-ubuntu.sh" BASE_IMAGE="djdeath/gputop-travis-ci-ubuntu16.04-18.01.09" - CONFIG_OPTS="--buildtype=release --cross=scripts/meson-cross/emscripten-docker-release.txt -Dwebui=true" PREP_SCRIPT="scripts/travis-ci-prep-docker-ubuntu.sh" BASE_IMAGE="djdeath/gputop-travis-ci-ubuntu16.04-18.01.09" - CONFIG_OPTS="--buildtype=debug" PREP_SCRIPT="scripts/travis-ci-prep-docker-centos.sh" BASE_IMAGE="djdeath/gputop-travis-ci-centos7-18.01.08" - CONFIG_OPTS="--buildtype=release" PREP_SCRIPT="scripts/travis-ci-prep-docker-centos.sh" BASE_IMAGE="djdeath/gputop-travis-ci-centos7-18.01.08" - CONFIG_OPTS="--buildtype=debug -Dnative_ui=true" PREP_SCRIPT="scripts/travis-ci-prep-docker-centos.sh" BASE_IMAGE="djdeath/gputop-travis-ci-centos7-18.01.08" - CONFIG_OPTS="--buildtype=release -Dnative_ui=true" PREP_SCRIPT="scripts/travis-ci-prep-docker-centos.sh" BASE_IMAGE="djdeath/gputop-travis-ci-centos7-18.01.08" before_install: - docker pull $BASE_IMAGE - $PREP_SCRIPT $BASE_IMAGE final-travis-ci-image script: - sudo docker run -t -i -v $TRAVIS_BUILD_DIR:/home/$USER/build -e TRAVIS_BUILD_DIR="/home/$USER/build" -e CONFIG_OPTS="$CONFIG_OPTS" final-travis-ci-image scripts/travis-ci-build.sh - sudo docker run -t -i -v $TRAVIS_BUILD_DIR:/home/$USER/build -e TRAVIS_BUILD_DIR="/home/$USER/build" -e CONFIG_OPTS="$CONFIG_OPTS" final-travis-ci-image scripts/travis-ci-test.sh deploy: provider: script script: ./scripts/deploy-demo-site.sh skip_cleanup: true on: condition: $CONFIG_OPTS = "--buildtype=release --cross=scripts/meson-cross/emscripten-docker-release.txt -Dwebui=true" branch: master ================================================ FILE: README.md ================================================ [![Build Status](https://travis-ci.org/rib/gputop.svg?branch=master)](https://travis-ci.org/rib/gputop) # gputop GPU Top is a tool to help developers understand GPU performance counters and provide graphical and machine readable data for the performance analysis of drivers and applications. GPU Top is compatible with all GPU programming apis such as OpenGL, OpenCL or Vulkan since it primarily deals with capturing periodic sampled metrics. GPU Top so far includes a web based interactive UI as well as a non-interactive CSV logging tool suited to being integrated into continuous regression testing systems. Both of these tools can capture metrics from a remote system so as to try an minimize their impact on the system being profiled. GPUs supported so far include: Haswell, Broadwell, Cherryview, Skylake, Broxton, Apollo Lake, Kabylake, Cannonlake and Coffeelake. It's not necessary to build the web UI from source to use it since the latest tested version is automatically deployed to http://gputop.github.io If you want to try out GPU Top on real hardware please follow these [build Instructions](https://github.com/rib/gputop/wiki/Build-Instructions) and give feedback [here](https://github.com/rib/gputop/issues). # Web UI Screenshot ![](https://raw.githubusercontent.com/wiki/rib/gputop/images/webui-imgui-screenshot.png) # Starting the GPU Top server Before you can use one of the clients, you need to start the GPU Top server. Since GPU Top is primarily a system wide analysis tool, you need to launch the server as root so that you can access information about any of the running processes using the GPU. You can done so by running : ``` sudo gputop ``` # CSV output example Here's an example from running `gputop-wrapper` like: ``` gputop-wrapper -m RenderBasic -c GpuCoreClocks,EuActive,L3Misses,GtiL3Throughput,EuFpuBothActive ``` Firstly the tool prints out a header that you might want to share with others to help ensure your comparing apples to apples when looking at metrics from different systems: ``` Server: localhost:7890 Sampling period: 1 s Monitoring system wide Connected System info: Kernel release: 4.15.0-rc4+ Kernel build: #49 SMP Tue Dec 19 12:17:49 GMT 2017 CPU info: CPU model: Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz CPU cores: 4 GPU info: GT name: Kabylake GT2 (Gen 9, PCI 0x5916) Topology: 168 threads, 24 EUs, 1 slices, 3 subslices GT frequency range: 0.0MHz / 0.0MHz CS timestamp frequency: 12000000 Hz / 83.33 ns OA info: OA Hardware Sampling Exponent: 22 OA Hardware Period: 699050666 ns / 699.1 ms ``` And then compactly prints the data collected. In this case the output was to a terminal and so the data is presented to be easily human readable. When output to a file then it will be a plain CSV file and numbers aren't rounded. ``` Timestamp GpuCoreClocks EuActive L3Misses GtiL3Throughput EuFpuBothActive (ns) (cycles/s) (%) (messages/s) (B) (%) 285961912416,770.9 M cycles, 0.919 %, 1473133.00, 89.91 MiB, 0.256 % 286992496416,900.1 M cycles, 1.04 %, 2036968.00, 124.3 MiB, 0.316 % 288190601500,521.4 M cycles, 1.81 %, 2030997.00, 124 MiB, 0.537 % 289519269500,1.028 G cycles, 11.8 %, 33181879.00, 1.978 GiB, 3.82 % 290562176250,1.007 G cycles, 11.1 %, 30115582.00, 1.795 GiB, 3.66 % 291569408333,905.9 M cycles, 10 %, 24534419.00, 1.462 GiB, 3.18 % 292590314500,762.4 M cycles, 6.89 %, 10934947.00, 667.4 MiB, 2.31 % 293954678166,538.5 M cycles, 1.72 %, 2034698.00, 124.2 MiB, 0.543 % 295323480416,751.6 M cycles, 1.28 %, 2034477.00, 124.2 MiB, 0.356 % ``` # Building GPU Top ## Dependencies GPUTop uses the meson build system. On a recent distribution you can install meson with : ``` sudo apt-get install meson ``` Alternatively you can use the pip distribution mechanism : ``` sudo pip3 install meson ``` GPU Top without UI tools has minimal dependencies : ``` sudo apt-get install libssl-dev pip2 install --user mako ``` If you want to build the GLFW UI, also install the following dependencies : ``` sudo apt-get install libgl1-mesa-dev libegl1-mesa-dev libglfw3-dev libepoxy-dev ``` A Gtk+ backend is also available for the UI (users with retina displays will want to use this), you'll need the following dependencies : ``` sudo apt-get install libsoup2.4-dev libcogl-dev libgtk-3-dev ``` ## Configuring the GPU Top build Without UI : ``` meson . build ``` With GLFW UI : ``` meson . build -Dnative_ui=true ``` With Gtk+ UI : ``` meson . build -Dnative_ui_gtk=true ``` ## Building GPU Top ``` ninja -C build ninja -C build install ``` ## Building GPU Top Web UI First make sure to have emscripten installed. GPU Top is currently only tested with version 1.37.27 of the emscripten SDK. Instructions to download the SDK are available here : https://kripken.github.io/emscripten-site/docs/getting_started/downloads.html After having run : ``` ./emsdk update ``` Install the tested version : ``` ./emsdk activate sdk-1.37.27-64bit ./emsdk install sdk-1.37.27-64bit ``` Then configure GPU Top to build the Web UI (in that mode it'll only build the UI, you'll need to build the server in the different build directory). ``` meson . build-webui -Dwebui=true --cross=scripts/meson-cross/emscripten-docker-debug.txt ``` Create a directory to serve the UI and copy the files needed : ``` mkdir webui cp ui/*.html ui/*.css ui/favicon.ico webui/ cp build-webui/ui/*.js build-webui/ui/*.wasm* build-webui/ui/gputop-ui.wast webui/ ``` You should now be able to serve the UI from the webui/ directory. ================================================ FILE: data/.gitignore ================================================ gputop-???.xml gputop-???gt?.xml i915_oa_*.[ch] package.json ================================================ FILE: data/Makefile.xml ================================================ data_dir = . script_dir = ../scripts oa_xml_files = \ oa-hsw.xml \ oa-bdw.xml \ oa-chv.xml \ oa-sklgt2.xml \ oa-sklgt3.xml \ oa-sklgt4.xml \ oa-bxt.xml \ oa-kblgt2.xml \ oa-kblgt3.xml \ oa-glk.xml \ oa-cflgt2.xml \ oa-cflgt3.xml \ oa-cnl.xml \ oa-icl.xml \ oa-lkf.xml \ oa-tgl.xml drm_files = $(oa_xml_files:oa-%.xml=i915_oa_%.c) drm_files += $(oa_xml_files:oa-%.xml=i915_oa_%.h) gputop_xml_files = $(oa_xml_files:oa-%.xml=gputop-%.xml) CONVERT_ARGS = KERNELGEN_ARGS = hsw_xml = mdapi/MetricsXML_HSW.xml bdw_xml = mdapi/MetricsXML_BDW.xml chv_xml = mdapi/MetricsXML_CHV.xml sklgt2_xml = mdapi/MetricsXML_SKL_GT2.xml sklgt3_xml = mdapi/MetricsXML_SKL_GT3.xml sklgt4_xml = mdapi/MetricsXML_SKL_GT4.xml bxt_xml = mdapi/MetricsXML_BXT.xml kblgt2_xml = mdapi/MetricsXML_KBL_GT2.xml kblgt3_xml = mdapi/MetricsXML_KBL_GT3.xml glk_xml = mdapi/MetricsXML_GLK.xml cflgt2_xml = mdapi/MetricsXML_CFL_GT2.xml cflgt3_xml = mdapi/MetricsXML_CFL_GT3.xml cnl_xml = mdapi/MetricsXML_CNL.xml icl_xml = mdapi/MetricsXML_ICL.xml lkf_xml = mdapi/MetricsXML_LKF.xml tgl_xml = mdapi/MetricsXML_TGL.xml INTERNAL=0 ifeq ($(INTERNAL), 1) hsw_xml += mdapi/MetricsXML_HSW_internal.xml bdw_xml += mdapi/MetricsXML_BDW_internal.xml chv_xml += mdapi/MetricsXML_CHV_internal.xml bxt_xml += mdapi/MetricsXML_BXT_internal.xml endif ifdef WHITELIST CONVERT_ARGS += --whitelist="$(WHITELIST)" KERNELGEN_ARGS += --whitelist="$(WHITELIST)" endif ifdef BLACKLIST CONVERT_ARGS += --blacklist="$(BLACKLIST)" KERNELGEN_ARGS += --blacklist="$(BLACKLIST)" endif SYSFS=1 ifeq ($(SYSFS), 1) KERNELGEN_ARGS += --sysfs endif GUIDS=$(data_dir)/guids.xml all: $(oa_xml_files) $(drm_files) oa-%.xml: mdapi/*.xml $(script_dir)/mdapi-xml-convert.py $(script_dir)/mdapi-xml-convert.py --guids=$(GUIDS) $(CONVERT_ARGS) $($(*)_xml) > $@ i915_oa_%.c i915_oa_%.h: oa-%.xml $(script_dir)/i915-perf-kernelgen.py $(script_dir)/i915-perf-kernelgen.py \ --guids=$(GUIDS) \ --chipset=$(*) \ --c-out=i915_oa_$(*).c \ --h-out=i915_oa_$(*).h \ $(KERNELGEN_ARGS) \ $(data_dir)/oa-$(*).xml distclean: -rm -f i915_oa_* clean: -rm -f i915_oa_* ================================================ FILE: data/README.md ================================================ # About guids.xml This is the authoritive registry of unique identifers for different OA unit hardware configurations. Userspace can reliably use these identifiers to map a configuration to corresponding normalization equations and counter meta data. If a hardware configuration ever changes in a backwards incompatible way (changing the semantics and/or layout of the raw counters) then it must be given a new GUID. mdapi-xml-convert.py will match metric sets with a GUID from this file based on an md5 hash of the hardware register configuration and skip a metric set with a warning if no GUID could be found. All new metric sets need to be allocated a GUID here before mdapi-xml-convert.py or i915-perf-kernelgen.py will output anything for that metric set. This ensures we don't automatically import new metric sets without some explicit review that that's appropriate. A failure to find a GUID for an older metric set most likely implies that the register configuration was changed. It's possible that the change is benign (e.g. a comment change) and in that case the mdapi_config_hash for the corresponding metric set below can be updated. The update-guids.py script is the recommended way of managing updates to this file by generate a temporary file with proposed updates that you can compare with the current guids.xml. # update-guids.xml update-guids.py can help with: * Recognising new metrics from VPG's MDAPI XML files *(NOTE: new guids.xml entries will initially be missing the config_hash=MD5_HASH attribute until mdapi-xml-convert.py is used to generate a corresponding oa-*.xml config description)* * Adding a config_hash=MD5_HASH attribute to recently added guids.xml entries after mdapi-xml-convert.py has been run. * Allocating a GUID for a custom metric that doesn't have a counterpart in VPG's MDAPI XML files. For this case you can add a stub entry with only a name like `` to guids.xml and then running update-guids.py will output a corresponding line with the addition of an id=UUID attribute. # How to sync the oa-\*.xml files with latest internal MDAPI XML files 1. E.g. copy a new `MetricsXML_BDW.xml` to `mdapi/MetricsXML_BDW.xml` *Note: that the `mdapi-xml-convert.py` script will only convert configs that have a corresponding GUID entry within `guids.xml`. This check helps avoid unintentionally publishing early, work-in-progress/pre-production configs.* The `guids.xml` registry maps each, complex OA unit register configuration to a unique ID that userspace can recognise and trust the semantics of raw counters read using that configuration. (Just for reference, this is particularly valuable for tools that capture raw metrics for later, offline processing since the IDs effectively provide a compressed description of how to interpret the data by providing an index into a database of high-level counter descriptions.) The registry associates each ID with a hash of the HW register config as found in MDAPI XML files ('mdapi_config_hash') and also with a hash of the HW config as found in oa-\*.xml files ('config_hash'). The hashes used for lookups in the registry also help detect when the register config for a pre-existing metric set is updated. Note: these hashes are only for the low-level hardware configuration so updates to counter descriptions used by fronted UIs won't affect indexing here. There is a chicken and egg situation when updating or adding new entries to guids.xml since we can't hash the configs in oa-\*.xml until successfully running mdapi-xml-convert.py which depends on a guids.xml registry entry first. The update-guids.xml script will output registry entries without an oa-\*.xml config hash if not available and can be re-run after mdapi-xml-convert.py to add the missing hashes. 2. Now run: ``` ../scripts/update-guids.py --guids=guids.xml mdapi/MetricsXML_BDW.xml > guids.xml2 ``` *(note the script expects to find oa-\*.xml files in the current directory)* Diff `guids.xml` and `guilds.xml2` (easiest with a side-by-side diff editor) and review the registry changes. *Note: many lines will have a warning like `"Not found in MDAPI XML file[s]..."` if `update-guids.xml` wasn't given all known MDAPI XML files but in this case they can be ignored for all non-BDW configs.* *Note: for any config that is already supported upstream in the i915 perf driver we need to be careful if the hash for a metric set changes in case the semantics for any raw counters were changed. The semantics of raw counters associated with a given GUID form part of the drm i915 perf uapi contract and must remain backwards compatible.* If the diff shows any `mdapi_config_hash` changes for pre-existing (especially upstream) configs you should review the MDAPI XML changes for the metric set and verify the change just relates to a bug fix. If more substantial changes were made which could mean we need to treat it as a new config. Handling the later case is left as an exercise to the reader, since it hasn't happened so far :-D. Assuming all the changes and new entries look good they can be copied into `guids.xml`, removing any trailing comment left by `update-guids.py`. 3. Now run mdapi-xml-convert.py: ``` ../scripts/mdapi-xml-convert.py --guids=guids.xml mdapi/MetricsXML_BDW.xml > oa-bdw.xml ``` 4. We can now update new entries in guids.xml with a 'config_hash': ``` ../scripts/update-guids.py --guids=guids.xml mdapi/MetricsXML_BDW.xml > guids.xml2 ``` *(and again diff, check the changes and copy across)* At this point other codegen can be done based on the update oa-\*.xml files such as genreating new i915 perf configs: ``` ../scripts/i915-perf-kernelgen.py --guids=guids.xml --chipset=bdw --c-out=i915_oa_bdw.c --h-out=i915_oa_bdw.h --sysfs oa-bdw.xml ``` ================================================ FILE: data/gputop.proto ================================================ syntax = "proto2"; package gputop; /* * To Browser */ enum EngineClass { OTHER = 0; RENDER = 1; COPY = 2; VIDEO = 3; VIDEO_ENHANCE = 4; } message DevTopology { required uint32 max_slices = 1; required uint32 max_subslices = 2; required uint32 max_eus_per_subslice = 3; required uint32 n_threads_per_eu = 4; required bytes slices_mask = 5; required bytes subslices_mask = 6; required bytes eus_mask = 7; repeated uint32 engines = 8; } message DevInfo { required uint32 devid = 1; required uint32 gen = 2; required uint64 timestamp_frequency = 3; required uint64 gt_min_freq = 4; required uint64 gt_max_freq = 5; required string devname = 6; required string prettyname = 7; required DevTopology topology = 8; } enum GLCounterType { RAW = 1; DURATION_RAW = 2; DURATION_NORM = 3; EVENT = 4; THROUGHPUT = 5; TIMESTAMP = 6; } enum GLCounterDataType { UINT64 = 1; UINT32 = 2; DOUBLE = 3; FLOAT = 4; BOOL32 = 5; } message GLCounter { required uint32 id = 1; required string name = 2; required string description = 3; required GLCounterType type = 4; required uint32 data_offset = 5; required GLCounterDataType data_type = 6; required uint64 maximum = 7; } message GLQueryInfo { required uint32 id = 1; required string name = 2; repeated GLCounter counters = 3; required uint32 data_size = 4; } message Features { required DevInfo devinfo = 1; required bool has_gl_performance_query = 2; /* implies single context view */ required bool has_i915_oa = 3; repeated GLQueryInfo gl_queries = 4; /* NB: Available OA queries are inferred from devinfo */ required uint32 n_cpus = 5; required string cpu_model = 6; required string kernel_release = 7; required string kernel_build = 8; required bool fake_mode = 9; repeated string supported_oa_uuids = 10; repeated string tracepoints = 11; repeated string notices = 12; required int32 server_pid = 13; repeated string events = 14; required bool has_i915_oa_cpu_timestamps = 15; required bool has_i915_oa_gpu_timestamps = 16; } message ProcessInfo { required uint32 pid = 1; required string cmd_line = 2; required string comm = 3; } message LogEntry { required uint32 log_level = 1; required string log_message = 2; //optional uint64 timestamp = 3; } message Log { repeated LogEntry entries = 1; } message CloseNotify { required uint32 id=1; } message BufferFillNotify { required uint32 stream_id=1; required uint32 fill_percentage=2; } message CpuStats { required uint64 timestamp = 1; required uint32 user = 2; required uint32 nice = 3; required uint32 system = 4; required uint32 idle = 5; required uint32 iowait = 6; required uint32 irq = 7; required uint32 softirq = 8; required uint32 steal = 9; required uint32 guest = 10; required uint32 guest_nice = 11; } message CpuStatsSet { required uint32 id = 1; /* handle used to open stream */ repeated CpuStats cpus = 2; } message TracepointInfo { required uint32 event_id = 1; required string sample_format = 2; } message Message { optional string reply_uuid = 1; oneof cmd { string error = 2; bool ack = 3; Features features = 4; Log log = 5; CloseNotify close_notify = 6; BufferFillNotify fill_notify = 7; ProcessInfo process_info = 8; CpuStatsSet cpu_stats = 9; TracepointInfo tracepoint_info = 10; } } /* * From Browser */ message OAStreamInfo { required string uuid = 1; //required uint32 format = 2; required uint32 period_exponent = 3; //TODO: allow specifying a specific context to profile required bool per_ctx_mode = 4; // Adds GPU timestamps in the i915 perf reports required bool gpu_timestamps = 5; // Adds CPU timestamps in the i915 perf reports required bool cpu_timestamps = 6; } message TracepointConfig { required int32 pid = 1; required int32 cpu = 2; required uint32 id = 3; } message GenericEventInfo { required int32 pid = 1; required int32 cpu = 2; required uint64 type = 3; //E.g. _TYPE_SOFTWARE or _TYPE_HARDWARE required uint64 config = 4; //E.g _COUNT_SW_CONTEXT_SWITCHES } message CpuStatsInfo { required uint32 sample_period_ms = 1; } message OpenStream { required uint32 id = 1; oneof type { uint32 gl_query = 2; OAStreamInfo oa_stream = 3; TracepointConfig tracepoint = 4; GenericEventInfo generic = 5; CpuStatsInfo cpu_stats = 9; } required bool overwrite = 6; required bool live_updates = 7; } message Request { required string uuid = 1; oneof req { bool get_features = 2; OpenStream open_stream = 3; uint32 close_stream = 4; uint32 get_process_info = 5; string test_log=6; string get_tracepoint_info = 7; } } ================================================ FILE: data/guids.xml ================================================ ================================================ FILE: data/oa-bdw.xml ================================================ ================================================ FILE: data/oa-bxt.xml ================================================ ================================================ FILE: data/oa-cflgt2.xml ================================================ ================================================ FILE: data/oa-cflgt3.xml ================================================ ================================================ FILE: data/oa-chv.xml ================================================ ================================================ FILE: data/oa-cnl.xml ================================================ ================================================ FILE: data/oa-glk.xml ================================================ ================================================ FILE: data/oa-hsw.xml ================================================ ================================================ FILE: data/oa-icl.xml ================================================ ================================================ FILE: data/oa-kblgt2.xml ================================================ ================================================ FILE: data/oa-kblgt3.xml ================================================ ================================================ FILE: data/oa-lkf.xml ================================================ ================================================ FILE: data/oa-sklgt2.xml ================================================ ================================================ FILE: data/oa-sklgt3.xml ================================================ ================================================ FILE: data/oa-sklgt4.xml ================================================ ================================================ FILE: data/oa-tgl.xml ================================================ ================================================ FILE: docker/travis-build-environment-centos/Dockerfile ================================================ FROM centos:7 RUN yum update -y && \ yum -y install epel-release && \ yum update -y && \ yum groupinstall -y 'Development Tools' && \ yum install -y \ git \ cmake3 \ python-libs \ ninja-build \ ca-certificates \ python-mako && \ yum clean all -y CMD ["/bin/bash"] ================================================ FILE: docker/travis-build-environment-centos/README.md ================================================ This Dockerfile was used to create a CentOS based Docker image that we use on Travis for building GPU Top that already contains an Emscripten toolchain. sudo docker build -t djdeath/gputop-travis-ci-centos . docker login docker push djdeath/gputop-travis-ci-centos7 ================================================ FILE: docker/travis-build-environment-centos/build-travis-docker-image.sh ================================================ #!/bin/sh docker build -t djdeath/gputop-travis-ci-centos7-18.01.08 . ================================================ FILE: docker/travis-build-environment-ubuntu/Dockerfile ================================================ FROM ubuntu:16.04 RUN apt-get update -y && apt-get install -y --no-install-recommends --no-install-suggests \ build-essential \ curl \ git \ cmake \ ninja-build \ python2.7-minimal \ libpython2.7-stdlib \ ca-certificates \ python-mako && \ apt-get clean # Download emscripten RUN mkdir -p /opt RUN cd /opt && curl https://s3.amazonaws.com/mozilla-games/emscripten/releases/emsdk-portable.tar.gz | tar xvz RUN cd /opt/emsdk-portable && ./emsdk install sdk-1.37.27-64bit RUN chmod go+rX -R /opt/emsdk-portable CMD ["/bin/bash"] ================================================ FILE: docker/travis-build-environment-ubuntu/README.md ================================================ This Dockerfile was used to create an Ubuntu based Docker image that we use on Travis for building GPU Top that already contains a pre-built LLVM fastcomp toolchain. sudo docker build -t djdeath/gputop-travis-ci-ubuntu16.04 . docker login docker push rib1/gputop-travis-ci-ubuntu16.04 ================================================ FILE: docker/travis-build-environment-ubuntu/build-travis-docker-image.sh ================================================ #!/bin/sh docker build -t djdeath/gputop-travis-ci-ubuntu16.04-18.01.09 . ================================================ FILE: gputop.doap ================================================ GPU Top Tool suite for displaying GPU performance statistics C Robert Bragg ================================================ FILE: lib/gputop-client-context.c ================================================ #include "gputop-client-context.h" #include #include #include #include "gputop-gens-metrics.h" #include "gputop-log.h" #include "main/hash.h" /* For uint_key() */ #include "util/ralloc.h" static void i915_perf_empty_samples(struct gputop_client_context *ctx); static void clear_perf_tracepoints_data(struct gputop_client_context *ctx); static void delete_process_entry(struct hash_entry *entry); int gputop_client_pretty_print_value(gputop_counter_units_t unit, double value, char *buffer, size_t length) { static const char *times[] = { "ns", "us", "ms", "s" }; static const char *bytes[] = { "B", "KiB", "MiB", "GiB" }; static const char *freqs[] = { "Hz", "KHz", "MHz", "GHz" }; static const char *texels[] = { "texels", "K texels", "M texels", "G texels" }; static const char *pixels[] = { "pixels", "K pixels", "M pixels", "G pixels" }; static const char *cycles[] = { "cycles", "K cycles", "M cycles", "G cycles" }; static const char *threads[] = { "threads", "K threads", "M threads", "G threads" }; const char **scales = NULL; switch (unit) { case GPUTOP_PERFQUERY_COUNTER_UNITS_BYTES: scales = bytes; break; case GPUTOP_PERFQUERY_COUNTER_UNITS_HZ: scales = freqs; break; case GPUTOP_PERFQUERY_COUNTER_UNITS_NS: case GPUTOP_PERFQUERY_COUNTER_UNITS_US: scales = times; break; case GPUTOP_PERFQUERY_COUNTER_UNITS_PIXELS: scales = pixels; break; case GPUTOP_PERFQUERY_COUNTER_UNITS_TEXELS: scales = texels; break; case GPUTOP_PERFQUERY_COUNTER_UNITS_THREADS: scales = threads; break; case GPUTOP_PERFQUERY_COUNTER_UNITS_CYCLES: scales = cycles; break; default: break; } int l; if (scales) { const double base = unit == GPUTOP_PERFQUERY_COUNTER_UNITS_BYTES ? 1024 : 1000; if (unit == GPUTOP_PERFQUERY_COUNTER_UNITS_US) value *= 1000; int i = 0; while (value >= base && i < 3) { value /= base; i++; } l = snprintf(buffer, length, "%.4g %s", value, scales ? scales[i] : ""); } else { if (unit == GPUTOP_PERFQUERY_COUNTER_UNITS_PERCENT) l = snprintf(buffer, length, "%.3g %%", value); else l = snprintf(buffer, length, "%.2f", value); } return l; } double gputop_client_context_max_value(struct gputop_client_context *ctx, const struct gputop_metric_set_counter *counter, uint64_t ns_time) { if (!counter->max_uint64 && !counter->max_float) return 0.0f; uint32_t counters0[64] = { 0, 1} ; uint32_t counters1[64] = { 0, 1 + gputop_time_scale_timebase(&ctx->devinfo, ns_time), 0, gputop_time_scale_timebase(&ctx->devinfo, ns_time), }; struct gputop_cc_oa_accumulator dummy_accumulator; gputop_cc_oa_accumulator_init(&dummy_accumulator, &ctx->devinfo, counter->metric_set, 0, NULL); gputop_cc_oa_accumulate_reports(&dummy_accumulator, (uint8_t *) counters0, (uint8_t *) counters1); double value; switch (counter->data_type) { case GPUTOP_PERFQUERY_COUNTER_DATA_UINT64: case GPUTOP_PERFQUERY_COUNTER_DATA_UINT32: case GPUTOP_PERFQUERY_COUNTER_DATA_BOOL32: value = counter->max_uint64(&ctx->devinfo, counter->metric_set, dummy_accumulator.deltas); break; case GPUTOP_PERFQUERY_COUNTER_DATA_DOUBLE: case GPUTOP_PERFQUERY_COUNTER_DATA_FLOAT: value = counter->max_float(&ctx->devinfo, counter->metric_set, dummy_accumulator.deltas); break; } return value; } int gputop_client_context_pretty_print_max(struct gputop_client_context *ctx, const struct gputop_metric_set_counter *counter, uint64_t ns_time, char *buffer, size_t length) { double value = gputop_client_context_max_value(ctx, counter, ns_time); if (value == 0.0f) return snprintf(buffer, length, "unknown"); return gputop_client_pretty_print_value(counter->units, value, buffer, length); } /**/ static void generate_uuid(struct gputop_client_context *ctx, char *out, size_t size, void *ptr) { snprintf(out, size, "%p", ptr); } /**/ struct protobuf_msg_closure; static void send_pb_message(struct gputop_client_context *ctx, ProtobufCMessage *pb_message) { if (!ctx->connection) return; size_t len = protobuf_c_message_get_packed_size(pb_message); uint8_t *data = (uint8_t *) malloc(len); protobuf_c_message_pack(pb_message, data); gputop_connection_send(ctx->connection, data, len); free(data); } /**/ static struct gputop_process_info * get_process_info(struct gputop_client_context *ctx, uint32_t pid) { struct hash_entry *entry = pid == 0 ? NULL : _mesa_hash_table_search(ctx->pid_to_process_table, uint_key(pid)); if (entry || pid == 0) return entry ? ((struct gputop_process_info *) entry->data) : NULL; struct gputop_process_info *info = (struct gputop_process_info *) calloc(1, sizeof(*info)); info->pid = pid; snprintf(info->cmd, sizeof(info->cmd), ""); _mesa_hash_table_insert(ctx->pid_to_process_table, uint_key(pid), info); list_addtail(&info->link, &ctx->process_infos); Gputop__Request request = GPUTOP__REQUEST__INIT; request.req_case = GPUTOP__REQUEST__REQ_GET_PROCESS_INFO; request.get_process_info = pid; send_pb_message(ctx, &request.base); return info; } static void update_hw_contexts_process_info(struct gputop_client_context *ctx, struct gputop_process_info *process) { list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { if (context->process != process) continue; snprintf(context->name, sizeof(context->name), "%s id=%u", process->cmd, context->hw_id); } } /**/ static void put_i915_perf_chunk(struct gputop_i915_perf_chunk *chunk) { if (!chunk || --chunk->refcount) return; list_del(&chunk->link); free(chunk); } static struct gputop_i915_perf_chunk * get_i915_perf_chunk(struct gputop_client_context *ctx, const uint8_t *data, size_t len) { struct gputop_i915_perf_chunk *chunk = (struct gputop_i915_perf_chunk *) malloc(len + sizeof(*chunk)); memcpy(chunk->data, data, len); chunk->length = len; chunk->refcount = 1; list_addtail(&chunk->link, &ctx->i915_perf_chunks); return chunk; } static struct gputop_i915_perf_chunk * ref_i915_perf_chunk(struct gputop_i915_perf_chunk *chunk) { chunk->refcount++; return chunk; } static uint64_t i915_perf_timestamp(struct gputop_client_context *ctx, const struct drm_i915_perf_record_header *header) { if (ctx->i915_perf_config.cpu_timestamps) { return *((uint64_t *) gputop_i915_perf_record_field( &ctx->i915_perf_config, header, GPUTOP_I915_PERF_FIELD_CPU_TIMESTAMP)); } uint64_t ts = gputop_cc_oa_report_get_timestamp( gputop_i915_perf_record_field(&ctx->i915_perf_config, header, GPUTOP_I915_PERF_FIELD_OA_REPORT)); uint64_t prev_ts = ctx->last_header ? gputop_cc_oa_report_get_timestamp( gputop_i915_perf_record_field(&ctx->i915_perf_config, ctx->last_header, GPUTOP_I915_PERF_FIELD_OA_REPORT)) : ts; ts = ctx->last_oa_timestamp + gputop_timebase_scale_ns(&ctx->devinfo, ts - prev_ts); return ts; } /**/ static void open_stream(struct gputop_stream *stream, struct gputop_client_context *ctx, Gputop__OpenStream *pb_open_stream) { stream->id = pb_open_stream->id = ctx->stream_id++; list_add(&stream->link, &ctx->streams); Gputop__Request request = GPUTOP__REQUEST__INIT; request.req_case = GPUTOP__REQUEST__REQ_OPEN_STREAM; request.open_stream = pb_open_stream; send_pb_message(ctx, &request.base); } static void close_stream(struct gputop_stream *stream, struct gputop_client_context *ctx) { if (stream->id == 0) return; Gputop__Request request = GPUTOP__REQUEST__INIT; request.req_case = GPUTOP__REQUEST__REQ_CLOSE_STREAM; request.close_stream = stream->id; send_pb_message(ctx, &request.base); list_del(&stream->link); memset(stream, 0, sizeof(*stream)); } static bool is_stream_opened(struct gputop_stream *stream) { return stream->id != 0; } static struct gputop_stream * find_stream(struct gputop_client_context *ctx, uint32_t stream_id) { list_for_each_entry(struct gputop_stream, stream, &ctx->streams, link) { if (stream->id == stream_id) return stream; } return NULL; } /**/ struct gputop_perf_tracepoint * gputop_client_context_add_tracepoint(struct gputop_client_context *ctx, const char *name) { struct hash_entry *entry = _mesa_hash_table_search(ctx->perf_tracepoints_name_table, name); if (entry) return (struct gputop_perf_tracepoint *) entry->data; struct gputop_perf_tracepoint *tp = (struct gputop_perf_tracepoint *) calloc(1, sizeof(*tp)); tp->hw_id_field = tp->process_field = -1; tp->idx = list_length(&ctx->perf_tracepoints); list_inithead(&tp->streams); list_inithead(&tp->data); snprintf(tp->name, sizeof(tp->name), "%s", name); generate_uuid(ctx, tp->uuid, sizeof(tp->uuid), tp); list_addtail(&tp->link, &ctx->perf_tracepoints); _mesa_hash_table_insert(ctx->perf_tracepoints_uuid_table, tp->uuid, tp); _mesa_hash_table_insert(ctx->perf_tracepoints_name_table, tp->name, tp); Gputop__Request request = GPUTOP__REQUEST__INIT; request.uuid = tp->uuid; request.req_case = GPUTOP__REQUEST__REQ_GET_TRACEPOINT_INFO; request.get_tracepoint_info = tp->name; send_pb_message(ctx, &request.base); return tp; } void gputop_client_context_print_tracepoint_data(struct gputop_client_context *ctx, char *buf, size_t len, struct gputop_perf_tracepoint_data *data, bool include_name) { struct gputop_perf_tracepoint *tp = data->tp; int l; if (include_name) { l = snprintf(buf, len, "%s: ", data->tp->name); buf += l; len -= l; } l = snprintf(buf, len, "cpu:%i", data->cpu); buf += l; len -= l; for (int f = 0; f < tp->n_fields; f++) { const char *name = tp->fields[f].name; if (!strcmp("common_type", name) || !strcmp("common_flags", name) || !strcmp("common_preempt_count", name)) continue; void *value_ptr = &data->data.data[tp->fields[f].offset]; l = 0; if (!strcmp("common_pid", name)) { uint32_t pid = *((uint32_t *) value_ptr); struct hash_entry *entry = _mesa_hash_table_search(ctx->pid_to_process_table, uint_key(pid)); l = snprintf(buf, len, "\npid = %u(%s)", pid, entry ? ((struct gputop_process_info *)entry->data)->cmd : ""); } else { switch (tp->fields[f].size) { case 1: if (tp->fields[f].is_signed) l = snprintf(buf, len, "\n%s = %hhd", name, *((int8_t *) value_ptr)); else l = snprintf(buf, len, "\n%s = %hhu", name, *((uint8_t *) value_ptr)); break; case 2: if (tp->fields[f].is_signed) l = snprintf(buf, len, "\n%s = %hd", name, *((int16_t *) value_ptr)); else l = snprintf(buf, len, "\n%s = %hu", name, *((uint16_t *) value_ptr)); break; case 4: if (tp->fields[f].is_signed) l = snprintf(buf, len, "\n%s = %d", name, *((int32_t *) value_ptr)); else l = snprintf(buf, len, "\n%s = %u", name, *((uint32_t *) value_ptr)); break; case 8: if (tp->fields[f].is_signed) l = snprintf(buf, len, "\n%s = %" PRIi64, name, *((int64_t *) value_ptr)); else l = snprintf(buf, len, "\n%s = %" PRIu64, name, *((uint64_t *) value_ptr)); break; } } if (l > 0) { buf += l; len -= l; } } } union value { char *string; int integer; }; struct parser_ctx { struct gputop_perf_tracepoint *tp; char *buffer; size_t len; int pos; }; #define YY_CTX_LOCAL #define YY_CTX_MEMBERS struct parser_ctx ctx; #define YYSTYPE union value #define YY_LOCAL(T) static __attribute__((unused)) T #define YY_PARSE(T) static T #define YY_INPUT(yy, buf, result, max) \ { \ int c = yy->ctx.pos < yy->ctx.len ? \ yy->ctx.buffer[yy->ctx.pos++] : EOF; \ result = (EOF == c) ? 0 : (*(buf) = c, 1); \ } #include "tracepoint_format.leg.h" static void update_tracepoint(struct gputop_perf_tracepoint *tp, const Gputop__TracepointInfo *info) { assert(tp->n_fields == 0); tp->event_id = info->event_id; tp->format = strdup(info->sample_format); tp->hw_id_field = tp->process_field = -1; yycontext ctx; memset(&ctx, 0, sizeof(ctx)); ctx.ctx.tp = tp; ctx.ctx.buffer = tp->format; ctx.ctx.len = strlen(tp->format); if (yyparse(&ctx)) { /* Only use i915_gem_request_add or i915_context_create for process * correlation. */ if (!strcmp(tp->name, "i915/i915_request_add") || !strcmp(tp->name, "i915/i915_request_submit") || !strcmp(tp->name, "i915/i915_context_create")) { for (int f = 0; f < tp->n_fields; f++) { if (!strcmp(tp->fields[f].name, "common_pid")) { tp->process_field = f; } else if (!strcmp(tp->fields[f].name, "hw_id")) { tp->hw_id_field = f; } } } } else tp->n_fields = 0; yyrelease(&ctx); } static void add_tracepoint_stream_data(struct gputop_client_context *ctx, struct gputop_perf_tracepoint_stream *stream, const uint8_t *data, size_t len) { struct gputop_perf_tracepoint *tp = stream->tp; struct gputop_perf_tracepoint_data *tp_data = (struct gputop_perf_tracepoint_data *) malloc(sizeof(*tp_data) - sizeof(tp_data->data) + len); tp_data->tp = tp; tp_data->cpu = stream->cpu; memcpy(&tp_data->data, data, len); /* Reunify the per cpu data into one global stream of tracepoints sorted * by time. */ struct gputop_perf_tracepoint_data *tp_end_data = list_empty(&ctx->perf_tracepoints_data) ? NULL : list_last_entry(&ctx->perf_tracepoints_data, struct gputop_perf_tracepoint_data, link); while (tp_end_data && tp_end_data->data.time > tp_data->data.time) { tp_end_data = (tp_end_data->link.prev == &ctx->perf_tracepoints_data) ? NULL : LIST_ENTRY(struct gputop_perf_tracepoint_data, tp_end_data->link.prev, link); } list_add(&tp_data->link, tp_end_data ? &tp_end_data->link : &ctx->perf_tracepoints_data); /* Also reunify the per cpu data into the stream of tracepoints sorted by * time. */ tp_end_data = list_empty(&tp->data) ? NULL : list_last_entry(&tp->data, struct gputop_perf_tracepoint_data, tp_link); while (tp_end_data && tp_end_data->data.time > tp_data->data.time) { tp_end_data = (tp_end_data->tp_link.prev == &tp->data) ? NULL : LIST_ENTRY(struct gputop_perf_tracepoint_data, tp_end_data->tp_link.prev, tp_link); } list_add(&tp_data->tp_link, tp_end_data ? &tp_end_data->tp_link : &tp->data); /* Remove tracepoints outside the sampling window. */ const uint64_t max_length = ctx->oa_visible_timeline_s * 1000000000ULL; struct gputop_perf_tracepoint_data *tp_start_data = list_first_entry(&ctx->perf_tracepoints_data, struct gputop_perf_tracepoint_data, link); tp_end_data = list_last_entry(&ctx->perf_tracepoints_data, struct gputop_perf_tracepoint_data, link); while ((tp_end_data->data.time - tp_start_data->data.time) > max_length) { list_del(&tp_start_data->link); list_del(&tp_start_data->tp_link); free(tp_start_data); tp_start_data = list_first_entry(&ctx->perf_tracepoints_data, struct gputop_perf_tracepoint_data, link); } if (tp->process_field >= 0) { uint32_t pid = *((uint32_t *)&tp_data->data.data[tp->fields[tp->process_field].offset]); struct gputop_process_info *process = get_process_info(ctx, pid); if (process && tp->hw_id_field >= 0) { uint32_t hw_id = *((uint32_t *)&tp_data->data.data[tp->fields[tp->hw_id_field].offset]); _mesa_hash_table_insert(ctx->hw_id_to_process_table, uint_key(hw_id), process); struct hash_entry *entry = _mesa_hash_table_search(ctx->hw_contexts_table, uint_key(hw_id)); if (entry) { struct gputop_hw_context *context = (struct gputop_hw_context *) entry->data; if (context->process != process) { context->process = process; if (process->cmd_line[0] != '\0') update_hw_contexts_process_info(ctx, process); } } } } } static void close_perf_tracepoint(struct gputop_client_context *ctx, struct gputop_perf_tracepoint *tp) { list_for_each_entry_safe(struct gputop_perf_tracepoint_stream, stream, &tp->streams, link) { list_del(&stream->link); _mesa_hash_table_remove(ctx->perf_tracepoints_stream_table, _mesa_hash_table_search(ctx->perf_tracepoints_stream_table, uint_key(stream->base.id))); close_stream(&stream->base, ctx); free(stream); } } static void open_perf_tracepoint(struct gputop_client_context *ctx, struct gputop_perf_tracepoint *tp) { close_perf_tracepoint(ctx, tp); Gputop__TracepointConfig pb_tp_config = GPUTOP__TRACEPOINT_CONFIG__INIT; pb_tp_config.pid = -1; pb_tp_config.id = tp->event_id; Gputop__OpenStream pb_stream = GPUTOP__OPEN_STREAM__INIT; pb_stream.overwrite = false; pb_stream.live_updates = true; pb_stream.type_case = GPUTOP__OPEN_STREAM__TYPE_TRACEPOINT; pb_stream.tracepoint = &pb_tp_config; for (int cpu = 0; cpu < ctx->features->features->n_cpus; cpu++) { pb_tp_config.cpu = cpu; struct gputop_perf_tracepoint_stream *stream = (struct gputop_perf_tracepoint_stream *) calloc(1, sizeof(struct gputop_perf_tracepoint_stream)); stream->tp = tp; stream->cpu = cpu; open_stream(&stream->base, ctx, &pb_stream); list_add(&stream->link, &tp->streams); _mesa_hash_table_insert(ctx->perf_tracepoints_stream_table, uint_key(stream->base.id), stream); } } void gputop_client_context_remove_tracepoint(struct gputop_client_context *ctx, struct gputop_perf_tracepoint *tp) { close_perf_tracepoint(ctx, tp); if (tp->format) free(tp->format); list_del(&tp->link); free(tp); int idx = 0; list_for_each_entry(struct gputop_perf_tracepoint, ltp, &ctx->perf_tracepoints, link) ltp->idx = idx++; } /**/ double gputop_client_context_calc_busyness(struct gputop_client_context *ctx) { double total = 0.0f; list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) total += context->usage_percent; return total; } uint64_t gputop_client_context_convert_gt_timestamp(struct gputop_client_context *ctx, uint32_t gt_timestamp) { list_for_each_entry(struct gputop_accumulated_samples, samples, &ctx->timelines, link) { uint32_t start_gt_ts = gputop_i915_perf_record_timestamp(&ctx->i915_perf_config, samples->start_report.header); uint32_t end_gt_ts = gputop_i915_perf_record_timestamp(&ctx->i915_perf_config, samples->end_report.header); if (end_gt_ts < gt_timestamp) continue; if (start_gt_ts > gt_timestamp) return 0ULL; uint32_t gt_delta = gt_timestamp - start_gt_ts; uint64_t delta = gt_delta * (samples->timestamp_end - samples->timestamp_start) / (end_gt_ts - start_gt_ts); return samples->timestamp_start + delta; } return 0ULL; } static struct gputop_accumulated_samples * get_accumulated_sample(struct gputop_client_context *ctx, struct gputop_i915_perf_chunk *chunk, const struct drm_i915_perf_record_header *header, uint32_t hw_id); static void put_accumulated_sample(struct gputop_client_context *ctx, struct gputop_accumulated_samples *samples); static void hw_context_update_process(struct gputop_client_context *ctx, struct gputop_hw_context *context) { if (context->process) return; struct hash_entry *process_entry = _mesa_hash_table_search(ctx->hw_id_to_process_table, uint_key(context->hw_id)); if (process_entry) { context->process = (struct gputop_process_info *) process_entry->data; snprintf(context->name, sizeof(context->name), "%s id=%u", context->process->cmd, context->hw_id); } } static struct gputop_hw_context * get_hw_context(struct gputop_client_context *ctx, uint32_t hw_id) { struct hash_entry *hw_entry = _mesa_hash_table_search(ctx->hw_contexts_table, uint_key(hw_id)); struct gputop_hw_context *new_context; if (hw_entry) { new_context = (struct gputop_hw_context *) hw_entry->data; new_context->n_samples++; hw_context_update_process(ctx, new_context); return new_context; } new_context = (struct gputop_hw_context *) calloc(1, sizeof(*new_context)); snprintf(new_context->name, sizeof(new_context->name), " id=%u", hw_id); new_context->hw_id = hw_id; new_context->timeline_row = _mesa_hash_table_num_entries(ctx->hw_contexts_table); new_context->n_samples = 1; list_inithead(&new_context->graphs); hw_context_update_process(ctx, new_context); new_context->current_graph_samples = get_accumulated_sample(ctx, ctx->current_graph_samples->start_report.chunk, ctx->current_graph_samples->start_report.header, GPUTOP_OA_INVALID_CTX_ID); _mesa_hash_table_insert(ctx->hw_contexts_table, uint_key(hw_id), new_context); list_addtail(&new_context->link, &ctx->hw_contexts); return new_context; } static void put_hw_context(struct gputop_client_context *ctx, struct gputop_hw_context *old_context) { if (!old_context || --old_context->n_samples) return; struct hash_entry *entry = _mesa_hash_table_search(ctx->hw_contexts_table, uint_key(old_context->hw_id)); _mesa_hash_table_remove(ctx->hw_contexts_table, entry); list_for_each_entry_safe(struct gputop_accumulated_samples, samples, &old_context->graphs, link) { put_accumulated_sample(ctx, samples); } if (old_context->current_graph_samples) put_accumulated_sample(ctx, old_context->current_graph_samples); list_del(&old_context->link); free(old_context); uint32_t i = 0; list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) context->timeline_row = i++; assert(i == _mesa_hash_table_num_entries(ctx->hw_contexts_table)); } static void hw_context_add_time(struct gputop_hw_context *context, struct gputop_accumulated_samples *samples, bool add) { uint64_t delta = samples->timestamp_end - samples->timestamp_start; context->time_spent += add ? delta : -delta; } static void hw_context_record_for_time(struct gputop_client_context *ctx, struct gputop_hw_context *context, struct gputop_i915_perf_chunk *chunk, const struct drm_i915_perf_record_header *header) { struct gputop_accumulated_samples *samples = context->current_graph_samples; assert(context->current_graph_samples != NULL); context->current_graph_samples = NULL; samples->end_report.chunk = ref_i915_perf_chunk(chunk); samples->end_report.header = header; /* Put end timestamp */ const uint64_t *cpu_timestamp = (const uint64_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, header, GPUTOP_I915_PERF_FIELD_CPU_TIMESTAMP); samples->timestamp_end = cpu_timestamp ? (*cpu_timestamp) : samples->accumulator.last_timestamp; uint64_t usage_ns = gputop_timebase_scale_ns(&ctx->devinfo, samples->accumulator.clock.clock_count); context->usage_percent = (double) usage_ns / ctx->oa_aggregation_period_ns; /* Remove excess of samples */ uint32_t max_graphs = (ctx->oa_visible_timeline_s * 1000000000.0f) / ctx->oa_aggregation_period_ns; while (context->n_graphs > max_graphs) { struct gputop_accumulated_samples *ex_samples = list_first_entry(&context->graphs, struct gputop_accumulated_samples, link); put_accumulated_sample(ctx, ex_samples); context->n_graphs--; } list_addtail(&samples->link, &context->graphs); context->n_graphs++; } static struct gputop_accumulated_samples * get_accumulated_sample(struct gputop_client_context *ctx, struct gputop_i915_perf_chunk *chunk, const struct drm_i915_perf_record_header *header, uint32_t hw_id) { struct gputop_accumulated_samples *samples; if (list_empty(&ctx->free_samples)) { samples = (struct gputop_accumulated_samples *) calloc(1, sizeof(*samples)); } else { samples = list_first_entry(&ctx->free_samples, struct gputop_accumulated_samples, link); list_del(&samples->link); memset(samples, 0, sizeof(*samples)); } const uint8_t *report = (const uint8_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, header, GPUTOP_I915_PERF_FIELD_OA_REPORT); gputop_cc_oa_accumulator_init(&samples->accumulator, &ctx->devinfo, ctx->metric_set, ctx->oa_aggregation_period_ns, report); list_inithead(&samples->link); samples->context = hw_id != GPUTOP_OA_INVALID_CTX_ID ? get_hw_context(ctx, hw_id) : NULL; samples->start_report.chunk = ref_i915_perf_chunk(chunk); samples->start_report.header = header; samples->timestamp_start = i915_perf_timestamp(ctx, header); return samples; } static void put_accumulated_sample(struct gputop_client_context *ctx, struct gputop_accumulated_samples *samples) { put_i915_perf_chunk(samples->start_report.chunk); put_i915_perf_chunk(samples->end_report.chunk); put_hw_context(ctx, samples->context); list_del(&samples->link); list_add(&samples->link, &ctx->free_samples); } void gputop_accumulated_samples_print(struct gputop_client_context *ctx, struct gputop_accumulated_samples *samples) { struct gputop_record_iterator iter; gputop_record_iterator_init(&iter, samples); const struct drm_i915_perf_record_header *last = NULL; while (gputop_record_iterator_next(&iter)) { if (iter.header->type != DRM_I915_PERF_RECORD_SAMPLE) continue; if (last) { const uint32_t *report = (const uint32_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, iter.header, GPUTOP_I915_PERF_FIELD_OA_REPORT); struct gputop_cc_oa_accumulator acc; gputop_cc_oa_accumulator_init(&acc, &ctx->devinfo, ctx->metric_set, 0, NULL); gputop_cc_oa_accumulate_reports(&acc, gputop_i915_perf_record_field(&ctx->i915_perf_config, last, GPUTOP_I915_PERF_FIELD_OA_REPORT), (const uint8_t *) report); switch (ctx->metric_set->perf_oa_format) { case I915_OA_FORMAT_A32u40_A4u32_B8_C8: fprintf(stderr, "TS=%lx %s\n", acc.deltas[0], gputop_i915_perf_record_reason(&ctx->i915_perf_config, &ctx->devinfo, iter.header)); fprintf(stderr, "CLK=%lx\n", acc.deltas[1]); /* /\* 32x 40bit A counters... *\/ */ /* for (i = 0; i < 32; i++) */ /* fprintf(stderr, "A%i=%lx\n", i, acc.deltas[i + 2]); */ /* /\* 4x 32bit A counters... *\/ */ /* for (i = 0; i < 4; i++) */ /* fprintf(stderr, "A%i=%lx\n", i, acc.deltas[i + 2 + 32]); */ /* /\* 8x 32bit B counters + 8x 32bit C counters... *\/ */ /* for (i = 0; i < 16; i++) */ /* fprintf(stderr, "B/C%i=%lx\n", i, acc.deltas[i + 2 + 32 + 4]); */ fprintf(stderr, "B/C%i=%x B/C%i=%x\n", 8, report[48], 9, report[49]); break; case I915_OA_FORMAT_A45_B8_C8: fprintf(stderr, "TS=%lx\n", acc.deltas[0]); /* for (i = 0; i < 61; i++) */ /* fprintf(stderr, "A%i=%lx\n", i, acc.deltas[i + 1]); */ break; default: assert(0); } } last = iter.header; } } double gputop_client_context_read_counter_value(struct gputop_client_context *ctx, struct gputop_accumulated_samples *sample, const struct gputop_metric_set_counter *counter) { switch (counter->data_type) { case GPUTOP_PERFQUERY_COUNTER_DATA_UINT64: case GPUTOP_PERFQUERY_COUNTER_DATA_UINT32: case GPUTOP_PERFQUERY_COUNTER_DATA_BOOL32: return counter->oa_counter_read_uint64(&ctx->devinfo, ctx->metric_set, sample->accumulator.deltas); break; case GPUTOP_PERFQUERY_COUNTER_DATA_DOUBLE: case GPUTOP_PERFQUERY_COUNTER_DATA_FLOAT: return counter->oa_counter_read_float(&ctx->devinfo, ctx->metric_set, sample->accumulator.deltas); break; } return 0.0f; } static void i915_perf_record_for_time(struct gputop_client_context *ctx, struct gputop_i915_perf_chunk *chunk, const struct drm_i915_perf_record_header *header) { struct gputop_accumulated_samples *samples = ctx->current_graph_samples; ctx->current_graph_samples = NULL; samples->end_report.chunk = ref_i915_perf_chunk(chunk); samples->end_report.header = header; /* Put end timestamp */ samples->timestamp_end = i915_perf_timestamp(ctx, header); /* Remove excess of samples */ uint32_t max_graphs = (ctx->oa_visible_timeline_s * 1000000000.0f) / ctx->oa_aggregation_period_ns; while (ctx->n_graphs > max_graphs) { struct gputop_accumulated_samples *ex_samples = list_first_entry(&ctx->graphs, struct gputop_accumulated_samples, link); put_accumulated_sample(ctx, ex_samples); ctx->n_graphs--; } list_addtail(&samples->link, &ctx->graphs); ctx->n_graphs++; } static void i915_perf_record_for_hw_id(struct gputop_client_context *ctx, struct gputop_i915_perf_chunk *chunk, const struct drm_i915_perf_record_header *header) { struct gputop_accumulated_samples *samples = ctx->current_timeline_samples; ctx->current_timeline_samples = NULL; samples->end_report.chunk = ref_i915_perf_chunk(chunk); samples->end_report.header = header; /* Put end timestamp */ samples->timestamp_end = i915_perf_timestamp(ctx, header); /* Remove excess of samples */ uint64_t aggregation_period_ns = ctx->oa_visible_timeline_s * 1000000000UL; struct gputop_accumulated_samples *first_samples = list_first_entry(&ctx->timelines, struct gputop_accumulated_samples, link); while (!list_empty(&ctx->timelines) && (samples->timestamp_end - first_samples->timestamp_start) > aggregation_period_ns) { hw_context_add_time(first_samples->context, first_samples, false); put_accumulated_sample(ctx, first_samples); ctx->n_timelines--; first_samples = list_first_entry(&ctx->timelines, struct gputop_accumulated_samples, link); } list_addtail(&samples->link, &ctx->timelines); ctx->n_timelines++; hw_context_add_time(samples->context, samples, true); } static void i915_perf_accumulate(struct gputop_client_context *ctx, struct gputop_i915_perf_chunk *chunk) { const struct drm_i915_perf_record_header *header; const uint8_t *last = ctx->last_header ? ((const uint8_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, ctx->last_header, GPUTOP_I915_PERF_FIELD_OA_REPORT)) : NULL; for (header = (const struct drm_i915_perf_record_header *) chunk->data; (const uint8_t *) header < (chunk->data + chunk->length); header = (const struct drm_i915_perf_record_header *) (((const uint8_t *)header) + header->size)) { switch (header->type) { case DRM_I915_PERF_RECORD_OA_BUFFER_LOST: gputop_cr_console_log("i915_oa: OA buffer error - all records lost"); gputop_client_context_stop_sampling(ctx); return; case DRM_I915_PERF_RECORD_OA_REPORT_LOST: if (ctx->warn_report_loss) gputop_cr_console_log("i915_oa: OA report lost"); break; case DRM_I915_PERF_RECORD_SAMPLE: { const uint8_t *samples = (const uint8_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, header, GPUTOP_I915_PERF_FIELD_OA_REPORT); uint32_t hw_id = gputop_cc_oa_report_get_ctx_id(&ctx->devinfo, samples); if (!ctx->current_graph_samples) { /* Global accumulator */ ctx->current_graph_samples = get_accumulated_sample(ctx, chunk, header, GPUTOP_OA_INVALID_CTX_ID); /* Also store an accumulator per context, only accumulated on */ list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { assert(context->current_graph_samples == NULL); context->current_graph_samples = get_accumulated_sample(ctx, chunk, header, GPUTOP_OA_INVALID_CTX_ID); } } if (last && ctx->last_hw_id != GPUTOP_OA_INVALID_CTX_ID && !ctx->current_timeline_samples) { ctx->current_timeline_samples = get_accumulated_sample(ctx, ctx->last_chunk, ctx->last_header, ctx->last_hw_id); } if (last) { struct gputop_cc_oa_accumulator *accumulator; if (ctx->current_timeline_samples) { struct gputop_hw_context *context = ctx->current_timeline_samples->context; /* Accumulate for the timeline on the currently running context. */ accumulator = &ctx->current_timeline_samples->accumulator; if (gputop_cc_oa_accumulate_reports(accumulator, last, samples)) { uint64_t elapsed = accumulator->last_timestamp - accumulator->first_timestamp; if (ctx->last_hw_id != hw_id || elapsed > (ctx->oa_aggregation_period_ns)) { i915_perf_record_for_hw_id(ctx, chunk, header); } } /* Accumulate for the running context over the * accumulation period. */ accumulator = &context->current_graph_samples->accumulator; gputop_cc_oa_accumulate_reports(accumulator, last, samples); } /* Accumulate globally over the accumulation period. */ accumulator = &ctx->current_graph_samples->accumulator; if (gputop_cc_oa_accumulate_reports(accumulator, last, samples)) { uint64_t elapsed = accumulator->last_timestamp - accumulator->first_timestamp; if (elapsed > (ctx->oa_aggregation_period_ns)) { i915_perf_record_for_time(ctx, chunk, header); if (ctx->accumulate_cb) ctx->accumulate_cb(ctx, NULL); list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { assert(context->current_graph_samples != NULL); hw_context_record_for_time(ctx, context, chunk, header); if (ctx->accumulate_cb) ctx->accumulate_cb(ctx, context); } } } } ctx->last_oa_timestamp = i915_perf_timestamp(ctx, header); last = samples; ctx->last_hw_id = hw_id; ctx->last_header = header; if (ctx->last_chunk) put_i915_perf_chunk(ctx->last_chunk); ctx->last_chunk = ref_i915_perf_chunk(chunk); break; } default: gputop_cr_console_log("i915 perf: Spurious header type = %d", header->type); return; } } } /**/ const struct gputop_metric_set * gputop_client_context_uuid_to_metric_set(struct gputop_client_context *ctx, const char *uuid) { struct hash_entry *entry = _mesa_hash_table_search(ctx->gen_metrics->metric_sets_map, uuid); return entry ? ((struct gputop_metric_set *) entry->data) : NULL; } const struct gputop_metric_set * gputop_client_context_symbol_to_metric_set(struct gputop_client_context *ctx, const char *symbol_name) { list_for_each_entry(struct gputop_metric_set, metric_set, &ctx->gen_metrics->metric_sets, link) { if (!strcmp(metric_set->symbol_name, symbol_name)) return metric_set; } return NULL; } static void build_equations_variables(struct gputop_devinfo *devinfo) { struct gputop_devtopology *topology = &devinfo->topology; int subslice_stride = DIV_ROUND_UP(topology->max_eus_per_subslice, 8); int slice_stride = subslice_stride * topology->max_subslices; int subslice_slice_stride = DIV_ROUND_UP(topology->max_subslices, 8); devinfo->n_eus = 0; for (int s = 0; s < topology->max_slices; s++) { for (int ss = 0; ss < topology->max_subslices; ss++) { for (int eug = 0; eug < subslice_stride; eug++) { devinfo->n_eus += __builtin_popcount(topology->eus_mask[slice_stride * s + subslice_stride * ss + eug]); } } } devinfo->n_eu_slices = 0; for (int s = 0; s < DIV_ROUND_UP(topology->max_slices, 8); s++) { devinfo->n_eu_slices += __builtin_popcount(topology->slices_mask[s]); } devinfo->n_eu_sub_slices = 0; for (int s = 0; s < topology->max_slices * subslice_slice_stride; s++) { devinfo->n_eu_sub_slices += __builtin_popcount(topology->subslices_mask[s]); } devinfo->slice_mask = topology->slices_mask[0]; /* Unfortunately the equations expect at $SubsliceMask variable were the * meaning of the bits varies from one platform to another. One could hope * that we get special operations to query slice/subslice availability * abstracting the storage of this information... */ int subslice_bits_per_slice = 0; if (devinfo->gen <= 10) { /* Subslices are grouped by 3. */ subslice_bits_per_slice = 3; } else if (devinfo->gen == 11) { /* Subslices are grouped by 8 */ subslice_bits_per_slice = 8; } else { unreachable("Cannot build subslice mask for equations"); } devinfo->subslice_mask = 0; for (int s = 0; s < topology->max_slices; s++) { for (int ss = 0; ss < MIN2(topology->max_subslices, 3); ss++) { bool enabled = (topology->subslices_mask[slice_stride * s + ss / 8] & (1UL << (ss % 8))) != 0; if (enabled) devinfo->subslice_mask |= 1ULL << (subslice_bits_per_slice * s + ss); } } devinfo->eu_threads_count = devinfo->n_eus * topology->n_threads_per_eu; } static void register_platform_metrics(struct gputop_client_context *ctx, const Gputop__DevInfo *pb_devinfo) { static const struct { const char *devname; struct gputop_gen * (*get_metrics_cb)(const struct gputop_devinfo *devinfo); } devname_to_metric_func[] = { { "hsw", gputop_oa_get_metrics_hsw }, { "bdw", gputop_oa_get_metrics_bdw }, { "chv", gputop_oa_get_metrics_chv }, { "sklgt2", gputop_oa_get_metrics_sklgt2 }, { "sklgt3", gputop_oa_get_metrics_sklgt3 }, { "sklgt4", gputop_oa_get_metrics_sklgt4 }, { "kblgt2", gputop_oa_get_metrics_kblgt2 }, { "kblgt3", gputop_oa_get_metrics_kblgt3 }, { "bxt", gputop_oa_get_metrics_bxt }, { "glk", gputop_oa_get_metrics_glk }, { "cflgt2", gputop_oa_get_metrics_cflgt2 }, { "cflgt3", gputop_oa_get_metrics_cflgt3 }, { "cnl", gputop_oa_get_metrics_cnl }, { "icl", gputop_oa_get_metrics_icl }, { "ehl", gputop_oa_get_metrics_lkf }, { "tgl", gputop_oa_get_metrics_tgl }, }; struct gputop_devinfo *devinfo = &ctx->devinfo; snprintf(devinfo->devname, sizeof(devinfo->devname), "%s", pb_devinfo->devname); snprintf(devinfo->prettyname, sizeof(devinfo->prettyname), "%s", pb_devinfo->prettyname); devinfo->timestamp_frequency = pb_devinfo->timestamp_frequency; devinfo->devid = pb_devinfo->devid; devinfo->gen = pb_devinfo->gen; devinfo->gt_min_freq = pb_devinfo->gt_min_freq; devinfo->gt_max_freq = pb_devinfo->gt_max_freq; const Gputop__DevTopology *pb_topology = pb_devinfo->topology; struct gputop_devtopology *topology = &ctx->devinfo.topology; memset(topology, 0, sizeof(*topology)); topology->max_slices = pb_topology->max_slices; topology->max_subslices = pb_topology->max_subslices; topology->max_eus_per_subslice = pb_topology->max_eus_per_subslice; topology->n_threads_per_eu = pb_topology->n_threads_per_eu; assert(pb_topology->slices_mask.len <= ARRAY_SIZE(topology->slices_mask)); for (uint32_t i = 0; i < pb_topology->slices_mask.len; i++) topology->slices_mask[i] = pb_topology->slices_mask.data[i]; assert(pb_topology->subslices_mask.len <= ARRAY_SIZE(topology->subslices_mask)); memcpy(topology->subslices_mask, pb_topology->subslices_mask.data, pb_topology->subslices_mask.len); assert(pb_topology->eus_mask.len <= ARRAY_SIZE(topology->eus_mask)); memcpy(topology->eus_mask, pb_topology->eus_mask.data, pb_topology->eus_mask.len); build_equations_variables(devinfo); for (uint32_t i = 0; i < ARRAY_SIZE(devname_to_metric_func); i++) { if (!strcmp(devinfo->devname, devname_to_metric_func[i].devname)) { ctx->gen_metrics = devname_to_metric_func[i].get_metrics_cb(devinfo); return; } } } /**/ static void close_i915_perf_stream(struct gputop_client_context *ctx) { if (is_stream_opened(&ctx->oa_stream)) close_stream(&ctx->oa_stream, ctx); } static void open_i915_perf_stream(struct gputop_client_context *ctx) { if (!ctx->metric_set) return; assert(!is_stream_opened(&ctx->oa_stream)); i915_perf_empty_samples(ctx); if (ctx->oa_sampling_period_ns > ctx->oa_aggregation_period_ns) { ctx->oa_sampling_period_ns = gputop_oa_exponent_to_period_ns( &ctx->devinfo, gputop_time_to_oa_exponent( &ctx->devinfo, ctx->oa_aggregation_period_ns)); } Gputop__OAStreamInfo oa_stream = GPUTOP__OASTREAM_INFO__INIT; oa_stream.uuid = (char *) ctx->metric_set->hw_config_guid; oa_stream.period_exponent = gputop_time_to_oa_exponent(&ctx->devinfo, ctx->oa_sampling_period_ns); oa_stream.per_ctx_mode = false; oa_stream.cpu_timestamps = ctx->i915_perf_config.cpu_timestamps; oa_stream.gpu_timestamps = ctx->i915_perf_config.gpu_timestamps; Gputop__OpenStream stream = GPUTOP__OPEN_STREAM__INIT; stream.overwrite = false; stream.live_updates = true; stream.type_case = GPUTOP__OPEN_STREAM__TYPE_OA_STREAM; stream.oa_stream = &oa_stream; open_stream(&ctx->oa_stream, ctx, &stream); } /**/ static void open_perf_events_streams(struct gputop_client_context *ctx) { // clear_perf_tracepoints_data(ctx); // list_for_each_entry(struct perf_event, tp, &ctx->perf_events, link) // open_perf_event(ctx, tp); } static void close_perf_events_streams(struct gputop_client_context *ctx) { // list_for_each_entry(struct perf_event, tp, &ctx->perf_events, link) // close_perf_event(ctx, tp); } /**/ static void open_perf_tracepoints_streams(struct gputop_client_context *ctx) { clear_perf_tracepoints_data(ctx); list_for_each_entry(struct gputop_perf_tracepoint, tp, &ctx->perf_tracepoints, link) { assert(list_length(&tp->data) == 0); open_perf_tracepoint(ctx, tp); } } static void close_perf_tracepoints_streams(struct gputop_client_context *ctx) { list_for_each_entry(struct gputop_perf_tracepoint, tp, &ctx->perf_tracepoints, link) close_perf_tracepoint(ctx, tp); } /**/ static void request_features(struct gputop_client_context *ctx) { Gputop__Request request = GPUTOP__REQUEST__INIT; request.req_case = GPUTOP__REQUEST__REQ_GET_FEATURES; request.get_features = true; send_pb_message(ctx, &request.base); } /**/ static bool add_cpu_stats(struct gputop_client_context *ctx, Gputop__Message *message) { if (!is_stream_opened(&ctx->cpu_stats_stream) || message->cpu_stats->id != ctx->cpu_stats_stream.id) return false; uint32_t max_cpu_stats = (ctx->cpu_stats_visible_timeline_s * 1000.0f) / ctx->cpu_stats_sampling_period_ms; struct gputop_cpu_stat *stat; /* Remove excess of samples */ while (ctx->n_cpu_stats > max_cpu_stats) { stat = list_first_entry(&ctx->cpu_stats, struct gputop_cpu_stat, link); list_del(&stat->link); gputop__message__free_unpacked(stat->stat, NULL); free(stat); ctx->n_cpu_stats--; } if (ctx->n_cpu_stats < max_cpu_stats) { stat = (struct gputop_cpu_stat *) calloc(1, sizeof(*stat)); ctx->n_cpu_stats++; } else { stat = list_first_entry(&ctx->cpu_stats, struct gputop_cpu_stat, link); list_del(&stat->link); gputop__message__free_unpacked(stat->stat, NULL); } stat->stat = message; list_addtail(&stat->link, &ctx->cpu_stats); return true; } static void open_cpu_stats_stream(struct gputop_client_context *ctx) { /**/ list_for_each_entry_safe(struct gputop_cpu_stat, stat, &ctx->cpu_stats, link) { list_del(&stat->link); gputop__message__free_unpacked(stat->stat, NULL); free(stat); } ctx->n_cpu_stats = 0; Gputop__CpuStatsInfo cpu_stats = GPUTOP__CPU_STATS_INFO__INIT; cpu_stats.sample_period_ms = ctx->cpu_stats_sampling_period_ms; Gputop__OpenStream stream = GPUTOP__OPEN_STREAM__INIT; stream.overwrite = false; stream.live_updates = true; stream.type_case = GPUTOP__OPEN_STREAM__TYPE_CPU_STATS; stream.cpu_stats = &cpu_stats; open_stream(&ctx->cpu_stats_stream, ctx, &stream); } void gputop_client_context_update_cpu_stream(struct gputop_client_context *ctx, int sampling_period_ms) { if (is_stream_opened(&ctx->cpu_stats_stream)) close_stream(&ctx->cpu_stats_stream, ctx); ctx->cpu_stats_sampling_period_ms = sampling_period_ms; open_cpu_stats_stream(ctx); } /**/ void gputop_client_context_stop_sampling(struct gputop_client_context *ctx) { if (!ctx->is_sampling) return; close_i915_perf_stream(ctx); close_perf_events_streams(ctx); close_perf_tracepoints_streams(ctx); ctx->is_sampling = false; } void gputop_client_context_start_sampling(struct gputop_client_context *ctx) { if (ctx->is_sampling) gputop_client_context_stop_sampling(ctx); _mesa_hash_table_clear(ctx->pid_to_process_table, delete_process_entry); _mesa_hash_table_clear(ctx->hw_id_to_process_table, NULL); open_i915_perf_stream(ctx); open_perf_events_streams(ctx); open_perf_tracepoints_streams(ctx); ctx->is_sampling = true; } /**/ static void handle_perf_data(struct gputop_client_context *ctx, uint32_t stream_id, const uint8_t *data, size_t len) { struct hash_entry *entry = _mesa_hash_table_search(ctx->perf_tracepoints_stream_table, uint_key(stream_id)); if (!entry) { gputop_cr_console_log("Unknown stream id=%u\n", stream_id); return; } struct gputop_perf_tracepoint_stream *stream = (struct gputop_perf_tracepoint_stream *) entry->data; const uint8_t *data_end = data + len; while (data < data_end) { const struct gputop_perf_data_tracepoint *point = (const struct gputop_perf_data_tracepoint *) data; add_tracepoint_stream_data(ctx, stream, data, point->header.size); data += point->header.size; } } static void handle_i915_perf_data(struct gputop_client_context *ctx, uint32_t stream_id, const uint8_t *data, size_t len) { if (stream_id == ctx->oa_stream.id) { struct gputop_i915_perf_chunk *chunk = get_i915_perf_chunk(ctx, data, len); i915_perf_accumulate(ctx, chunk); put_i915_perf_chunk(chunk); } else gputop_cr_console_log("discard wrong oa stream id=%i/%i", stream_id, ctx->oa_stream.id); } static void log_add(struct gputop_client_context *ctx, int level, const char *msg) { if (ctx->n_messages < ARRAY_SIZE(ctx->messages)) { ctx->messages[ctx->n_messages].level = level; ctx->messages[ctx->n_messages].msg = strdup(msg); ctx->n_messages++; } else { int idx = (++ctx->start_message + ctx->n_messages) % ARRAY_SIZE(ctx->messages); free(ctx->messages[idx].msg); ctx->messages[idx].level = level; ctx->messages[idx].msg = strdup(msg); } } static void handle_protobuf_message(struct gputop_client_context *ctx, const uint8_t *data, size_t len) { Gputop__Message *message = (Gputop__Message *) protobuf_c_message_unpack(&gputop__message__descriptor, NULL, /* default allocator */ len, data); if (!message) { gputop_cr_console_log("Failed to unpack message len=%u", len); return; } switch (message->cmd_case) { case GPUTOP__MESSAGE__CMD_ERROR: log_add(ctx, 0, message->error); break; case GPUTOP__MESSAGE__CMD_ACK: //gputop_cr_console_log("ack\n"); break; case GPUTOP__MESSAGE__CMD_FEATURES: if (ctx->features) gputop__message__free_unpacked(ctx->features, NULL); ctx->features = message; register_platform_metrics(ctx, message->features->devinfo); ctx->i915_perf_config.cpu_timestamps = message->features->has_i915_oa_cpu_timestamps && message->features->has_i915_oa_gpu_timestamps; ctx->i915_perf_config.gpu_timestamps = message->features->has_i915_oa_cpu_timestamps && message->features->has_i915_oa_gpu_timestamps; message = NULL; /* Save that structure for internal use */ break; case GPUTOP__MESSAGE__CMD_LOG: for (size_t i = 0; i < message->log->n_entries; i++) { log_add(ctx, message->log->entries[i]->log_level, message->log->entries[i]->log_message); } break; case GPUTOP__MESSAGE__CMD_CLOSE_NOTIFY: { struct gputop_stream *stream = find_stream(ctx, message->close_notify->id); if (stream) gputop_cr_console_log("unexpected close notify id=%i", message->close_notify->id); break; } case GPUTOP__MESSAGE__CMD_FILL_NOTIFY: { struct gputop_stream *stream = find_stream(ctx, message->fill_notify->stream_id); if (stream) stream->fill = message->fill_notify->fill_percentage; break; } case GPUTOP__MESSAGE__CMD_PROCESS_INFO: { struct hash_entry *entry = _mesa_hash_table_search(ctx->pid_to_process_table, uint_key(message->process_info->pid)); if (entry) { struct gputop_process_info *info = (struct gputop_process_info *) entry->data; snprintf(info->cmd, sizeof(info->cmd), "%s", message->process_info->comm); snprintf(info->cmd_line, sizeof(info->cmd_line), "%s", message->process_info->cmd_line); update_hw_contexts_process_info(ctx, info); } break; } case GPUTOP__MESSAGE__CMD_CPU_STATS: if (add_cpu_stats(ctx, message)) message = NULL; break; case GPUTOP__MESSAGE__CMD_TRACEPOINT_INFO: { if (ctx->tracepoint_info) gputop__message__free_unpacked(ctx->tracepoint_info, NULL); ctx->tracepoint_info = message; struct hash_entry *entry = _mesa_hash_table_search(ctx->perf_tracepoints_uuid_table, message->reply_uuid); if (entry) { update_tracepoint((struct gputop_perf_tracepoint *) entry->data, message->tracepoint_info); } message = NULL; break; } case GPUTOP__MESSAGE__CMD__NOT_SET: assert(0); } if (message) gputop__message__free_unpacked(message, NULL); } void gputop_client_context_handle_data(struct gputop_client_context *ctx, const void *payload, size_t payload_len) { const uint8_t *msg_type = (const uint8_t *) payload; const uint8_t *data = (const uint8_t *) payload + 8; size_t len = payload_len - 8; switch (*msg_type) { case 1: { const uint32_t *stream_id = (const uint32_t *) ((const uint8_t *) payload + 4); handle_perf_data(ctx, *stream_id, data, len); break; } case 2: handle_protobuf_message(ctx, data, len); break; case 3: { const uint32_t *stream_id = (const uint32_t *) ((const uint8_t *) payload + 4); handle_i915_perf_data(ctx, *stream_id, data, len); break; } default: gputop_cr_console_log("unknown msg type=%hhi", *msg_type); break; } } static void i915_perf_empty_samples(struct gputop_client_context *ctx) { list_for_each_entry_safe(struct gputop_accumulated_samples, samples, &ctx->timelines, link) { put_accumulated_sample(ctx, samples); } if (ctx->current_timeline_samples) { put_accumulated_sample(ctx, ctx->current_timeline_samples); ctx->current_timeline_samples = NULL; } _mesa_hash_table_clear(ctx->hw_contexts_table, NULL); ctx->n_timelines = 0; ctx->last_hw_id = GPUTOP_OA_INVALID_CTX_ID; list_for_each_entry_safe(struct gputop_accumulated_samples, samples, &ctx->graphs, link) { put_accumulated_sample(ctx, samples); } if (ctx->current_graph_samples) { put_accumulated_sample(ctx, ctx->current_graph_samples); ctx->current_graph_samples = NULL; } assert(list_empty(&ctx->graphs)); ctx->n_graphs = 0; if (ctx->last_chunk) { put_i915_perf_chunk(ctx->last_chunk); ctx->last_chunk = NULL; } ctx->last_header = NULL; /* Make sure to leave some room for the UI to present timelines sliding * from the right hand side of the timeline view. */ ctx->last_oa_timestamp = ctx->oa_visible_timeline_s * 1000000000ULL; assert(list_empty(&ctx->i915_perf_chunks)); } static void delete_process_entry(struct hash_entry *entry) { struct gputop_process_info *info = entry->data; list_del(&info->link); free(info); } static void clear_perf_tracepoints_data(struct gputop_client_context *ctx) { list_for_each_entry_safe(struct gputop_perf_tracepoint_data, data, &ctx->perf_tracepoints_data, link) { list_del(&data->link); list_del(&data->tp_link); free(data); } } void gputop_client_context_clear_logs(struct gputop_client_context *ctx) { for (int i = 0; i < ctx->n_messages; i++) free(ctx->messages[i].msg); ctx->start_message = ctx->n_messages = 0; } void gputop_client_context_init(struct gputop_client_context *ctx) { list_inithead(&ctx->cpu_stats); ctx->cpu_stats_visible_timeline_s = 7.0f; ctx->cpu_stats_sampling_period_ms = 100; ctx->oa_visible_timeline_s = 7.0f; ctx->oa_aggregation_period_ns = 60000000ULL; /* 60ms */ ctx->oa_sampling_period_ns = 1000000ULL; /* 1ms */ list_inithead(&ctx->streams); ctx->hw_contexts_table = _mesa_hash_table_create(NULL, _mesa_hash_pointer, _mesa_key_pointer_equal); _mesa_hash_table_set_deleted_key(ctx->hw_contexts_table, uint_key(UINT32_MAX)); _mesa_hash_table_set_freed_key(ctx->hw_contexts_table, uint_key(UINT32_MAX - 1)); list_inithead(&ctx->hw_contexts); list_inithead(&ctx->graphs); list_inithead(&ctx->timelines); list_inithead(&ctx->free_samples); list_inithead(&ctx->i915_perf_chunks); list_inithead(&ctx->perf_tracepoints); list_inithead(&ctx->perf_tracepoints_data); ctx->perf_tracepoints_name_table = _mesa_hash_table_create(NULL, _mesa_hash_string, _mesa_key_string_equal); ctx->perf_tracepoints_uuid_table = _mesa_hash_table_create(NULL, _mesa_hash_string, _mesa_key_string_equal); ctx->perf_tracepoints_stream_table = _mesa_hash_table_create(NULL, _mesa_hash_pointer, _mesa_key_pointer_equal); ctx->pid_to_process_table = _mesa_hash_table_create(NULL, _mesa_hash_pointer, _mesa_key_pointer_equal); ctx->hw_id_to_process_table = _mesa_hash_table_create(NULL, _mesa_hash_pointer, _mesa_key_pointer_equal); _mesa_hash_table_set_deleted_key(ctx->pid_to_process_table, uint_key(UINT32_MAX)); _mesa_hash_table_set_freed_key(ctx->pid_to_process_table, uint_key(UINT32_MAX - 1)); _mesa_hash_table_set_deleted_key(ctx->hw_id_to_process_table, uint_key(UINT32_MAX)); _mesa_hash_table_set_freed_key(ctx->hw_id_to_process_table, uint_key(UINT32_MAX - 1)); list_inithead(&ctx->process_infos); ctx->i915_perf_config.oa_reports = true; } void gputop_client_context_reset(struct gputop_client_context *ctx, gputop_connection_t *connection) { if (is_stream_opened(&ctx->cpu_stats_stream)) list_inithead(&ctx->streams); /* Nuclear option... */ /**/ i915_perf_empty_samples(ctx); clear_perf_tracepoints_data(ctx); assert(list_length(&ctx->perf_tracepoints_data) == 0); /**/ if (ctx->features) { gputop__message__free_unpacked(ctx->features, NULL); ctx->features = NULL; } if (ctx->tracepoint_info) { gputop__message__free_unpacked(ctx->tracepoint_info, NULL); ctx->tracepoint_info = NULL; } ralloc_free(ctx->gen_metrics); ctx->gen_metrics = NULL; ctx->metric_set = NULL; assert(list_length(&ctx->hw_contexts) == 0); assert(list_length(&ctx->streams) == 0); ctx->selected_uuid = -1; _mesa_hash_table_clear(ctx->perf_tracepoints_name_table, NULL); _mesa_hash_table_clear(ctx->perf_tracepoints_uuid_table, NULL); list_for_each_entry_safe(struct gputop_perf_tracepoint, tp, &ctx->perf_tracepoints, link) { gputop_client_context_remove_tracepoint(ctx, tp); } assert(list_length(&ctx->perf_tracepoints) == 0); /**/ _mesa_hash_table_clear(ctx->pid_to_process_table, delete_process_entry); _mesa_hash_table_clear(ctx->hw_id_to_process_table, NULL); gputop_client_context_clear_logs(ctx); ctx->stream_id = 1; /* 0 reserved for closed/invalid */ ctx->connection = connection; if (connection) { request_features(ctx); open_cpu_stats_stream(ctx); } } ================================================ FILE: lib/gputop-client-context.h ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __GPUTOP_CLIENT_CONTEXT_H__ #define __GPUTOP_CLIENT_CONTEXT_H__ #include #include #include "util/hash_table.h" #include "util/list.h" #include "gputop-network.h" #include "gputop-oa-counters.h" #include "gputop-oa-metrics.h" #include "gputop.pb-c.h" #ifdef __cplusplus extern "C" { #endif /* A chunk of data coming from the i915 perf driver (contains a sequence of * struct drm_i915_perf_record_header fields). */ struct gputop_i915_perf_chunk { struct list_head link; uint32_t refcount; uint32_t length; uint8_t data[]; }; struct gputop_accumulated_samples; struct gputop_process_info; struct gputop_hw_context { char name[300]; uint32_t hw_id; uint32_t n_samples; uint64_t time_spent; struct list_head link; struct gputop_process_info *process; struct gputop_accumulated_samples *current_graph_samples; struct list_head graphs; /* list of gputop_accumulated_samples */ uint32_t n_graphs; /* UI state */ uint64_t visible_time_spent; uint64_t visible_time; double usage_percent; uint32_t timeline_row; bool selected; }; struct gputop_accumulated_samples { struct list_head link; struct gputop_hw_context *context; /* Correlated in CPU clock if available or OA timestamp scaled into * nanoseconds. */ uint64_t timestamp_start; uint64_t timestamp_end; struct { struct gputop_i915_perf_chunk *chunk; const struct drm_i915_perf_record_header *header; } start_report, end_report; struct gputop_cc_oa_accumulator accumulator; }; struct gputop_cpu_stat { struct list_head link; Gputop__Message *stat; }; struct gputop_stream { struct list_head link; int id; float fill; }; struct gputop_perf_event { struct list_head link; /* global list (gputop_client_context.perf_events) */ char name[128]; uint32_t event_id; struct list_head streams; /* list of gputop_perf_event_stream */ }; struct gputop_perf_event_data { struct { uint32_t type; uint16_t misc; uint16_t size; } header; uint64_t time; uint64_t value; }; struct gputop_perf_event_stream { struct gputop_stream base; int cpu; struct gputop_perf_event *event; struct gputop_perf_event_data *data; struct list_head link; /* list of streams (gputop_perf_tracepoint.streams) */ }; struct gputop_perf_data_tracepoint { struct { uint32_t type; uint16_t misc; uint16_t size; } header; uint64_t time; uint32_t data_size; uint8_t data[]; }; struct gputop_perf_tracepoint { struct list_head link; /* global list (gputop_client_context.perf_tracepoints)*/ struct list_head data; /* list of gputop_perf_tracepoint_data */ char name[128]; uint32_t event_id; char *format; int idx; char uuid[20]; struct { bool is_signed; int offset; int size; char name[80]; } fields[20]; int n_fields; int process_field; int hw_id_field; struct list_head streams; /* list of gputop_perf_tracepoint_stream */ }; struct gputop_perf_tracepoint_stream { struct gputop_stream base; int cpu; struct gputop_perf_tracepoint *tp; struct list_head link; /* list of streams (gputop_perf_tracepoint.streams) */ }; struct gputop_perf_tracepoint_data { struct list_head link; /* global list (gputop_client_context.perf_tracepoints_data) */ struct list_head tp_link; /* per tracepoint list (gputop_perf_tracepoint.data) */ struct gputop_perf_tracepoint *tp; int cpu; struct gputop_perf_data_tracepoint data; }; struct gputop_process_info { struct list_head link; char cmd[256]; char cmd_line[1024]; uint32_t pid; }; struct gputop_client_context; typedef void (*gputop_accumulate_cb)(struct gputop_client_context *ctx, struct gputop_hw_context *context); struct gputop_client_context { gputop_connection_t *connection; struct list_head streams; bool is_sampling; /**/ Gputop__Message *features; Gputop__Message *tracepoint_info; struct gputop_gen *gen_metrics; struct gputop_devinfo devinfo; int selected_uuid; /**/ struct list_head cpu_stats; int n_cpu_stats; float cpu_stats_visible_timeline_s; /* RW */ int cpu_stats_sampling_period_ms; struct gputop_stream cpu_stats_stream; /**/ struct gputop_i915_perf_configuration i915_perf_config; const struct gputop_metric_set *metric_set; struct gputop_i915_perf_chunk *last_chunk; const struct drm_i915_perf_record_header *last_header; struct gputop_stream oa_stream; struct list_head free_samples; struct list_head i915_perf_chunks; uint64_t last_oa_timestamp; /**/ struct gputop_accumulated_samples *current_graph_samples; struct list_head graphs; int n_graphs; float oa_visible_timeline_s; /* RW */ uint64_t oa_aggregation_period_ns; /* RW (when not sampling) */ uint64_t oa_sampling_period_ns; /* RW (when not sampling), always <= oa_aggregation_period_ns */ gputop_accumulate_cb accumulate_cb; /* RW */ bool warn_report_loss; /* RW */ /**/ struct gputop_accumulated_samples *current_timeline_samples; struct list_head timelines; int n_timelines; uint32_t last_hw_id; struct hash_table *hw_contexts_table; struct list_head hw_contexts; /**/ struct hash_table *perf_tracepoints_uuid_table; struct hash_table *perf_tracepoints_name_table; struct hash_table *perf_tracepoints_stream_table; struct list_head perf_tracepoints; struct list_head perf_tracepoints_data; /**/ struct hash_table *perf_events_stream_table; struct list_head perf_events; /**/ struct hash_table *pid_to_process_table; struct hash_table *hw_id_to_process_table; struct list_head process_infos; /**/ struct { int level; char *msg; } messages[100]; int start_message; int n_messages; /**/ uint32_t stream_id; }; int gputop_client_pretty_print_value(gputop_counter_units_t unit, double value, char *buffer, size_t length); double gputop_client_context_max_value(struct gputop_client_context *ctx, const struct gputop_metric_set_counter *counter, uint64_t ns_time); int gputop_client_context_pretty_print_max(struct gputop_client_context *ctx, const struct gputop_metric_set_counter *counter, uint64_t ns_time, char *buffer, size_t length); void gputop_client_context_init(struct gputop_client_context *ctx); void gputop_client_context_reset(struct gputop_client_context *ctx, gputop_connection_t *connection); void gputop_client_context_handle_data(struct gputop_client_context *ctx, const void *payload, size_t payload_len); void gputop_client_context_update_cpu_stream(struct gputop_client_context *ctx, int sampling_period_ms); void gputop_client_context_stop_sampling(struct gputop_client_context *ctx); void gputop_client_context_start_sampling(struct gputop_client_context *ctx); void gputop_client_context_clear_logs(struct gputop_client_context *ctx); const struct gputop_metric_set * gputop_client_context_uuid_to_metric_set(struct gputop_client_context *ctx, const char *uuid); const struct gputop_metric_set * gputop_client_context_symbol_to_metric_set(struct gputop_client_context *ctx, const char *symbol_name); struct gputop_perf_tracepoint * gputop_client_context_add_tracepoint(struct gputop_client_context *ctx, const char *name); void gputop_client_context_remove_tracepoint(struct gputop_client_context *ctx, struct gputop_perf_tracepoint *tp); void gputop_client_context_print_tracepoint_data(struct gputop_client_context *ctx, char *buf, size_t len, struct gputop_perf_tracepoint_data *data, bool include_name); double gputop_client_context_read_counter_value(struct gputop_client_context *ctx, struct gputop_accumulated_samples *sample, const struct gputop_metric_set_counter *counter); uint64_t gputop_client_context_convert_gt_timestamp(struct gputop_client_context *ctx, uint32_t gt_timestamp); double gputop_client_context_calc_busyness(struct gputop_client_context *ctx); void gputop_accumulated_samples_print(struct gputop_client_context *ctx, struct gputop_accumulated_samples *sample); /* Iterator for reports accumulated into gputop_accumulated_samples. */ struct gputop_record_iterator { const struct gputop_accumulated_samples *sample; const struct gputop_i915_perf_chunk *chunk; const struct drm_i915_perf_record_header *header; bool done; }; static inline void gputop_record_iterator_init(struct gputop_record_iterator *iter, const struct gputop_accumulated_samples *sample) { iter->sample = sample; iter->chunk = NULL; iter->header = NULL; iter->done = false; } static inline bool gputop_record_iterator_next(struct gputop_record_iterator *iter) { if (iter->done) return false; if (!iter->header) { iter->chunk = iter->sample->start_report.chunk; iter->header = iter->sample->start_report.header; return true; } const struct drm_i915_perf_record_header *new_header = (const struct drm_i915_perf_record_header *) ((const uint8_t *) iter->header + iter->header->size); if ((const uint8_t *) new_header < (iter->chunk->data + iter->chunk->length)) { iter->header = new_header; iter->done = iter->header == iter->sample->end_report.header; return true; } if (!iter->sample->end_report.chunk || iter->sample->start_report.chunk == iter->sample->end_report.chunk) { iter->done = true; return false; } iter->chunk = list_first_entry(&iter->chunk->link, struct gputop_i915_perf_chunk, link); iter->header = (const struct drm_i915_perf_record_header *) iter->chunk->data; iter->done = iter->header == iter->sample->end_report.header; return true; } #ifdef __cplusplus } /* extern "C" */ #endif #endif /* __GPUTOP_CLIENT_CONTEXT_H__ */ ================================================ FILE: lib/gputop-log.h ================================================ /* * GPU Top * * Copyright (C) 2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include #include #include #include "util/list.h" #include "gputop.pb-c.h" #ifdef GPUTOP_ENABLE_DEBUG #define dbg(format, ...) do { \ char *message; \ int ret = asprintf(&message, format, ##__VA_ARGS__); \ (void) ret; \ gputop_log(GPUTOP_LOG_LEVEL_NOTIFICATION, message, -1); \ free(message); \ } while(0) #else #define dbg(format, ...) do { } while(0) #endif #define server_dbg(format, ...) do { \ fprintf(stderr, format, ##__VA_ARGS__); \ } while(0) extern pthread_once_t gputop_log_init_once; extern pthread_rwlock_t gputop_log_lock; extern int gputop_log_len; extern struct list_head gputop_log_entries; enum gputop_log_level { GPUTOP_LOG_LEVEL_HIGH = 1, GPUTOP_LOG_LEVEL_MEDIUM, GPUTOP_LOG_LEVEL_LOW, GPUTOP_LOG_LEVEL_NOTIFICATION, }; struct gputop_log_entry { struct list_head link; char *msg; int level; }; void gputop_log_init(void); void gputop_log(int level, const char *message, int len); Gputop__Log *gputop_get_pb_log(void); void gputop_pb_log_free(Gputop__Log *log); void gputop_cr_console_log(const char *format, ...); ================================================ FILE: lib/gputop-network.h ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __GPUTOP_NETWORK_H__ #define __GPUTOP_NETWORK_H__ #include #include #ifdef __cplusplus extern "C" { #endif /* This interface should be implemented by the embedder. */ typedef struct _gputop_connection_t gputop_connection_t; typedef void (*gputop_on_ready_cb_t)(gputop_connection_t *conn, void *user_data); typedef void (*gputop_on_data_cb_t)(gputop_connection_t *conn, const void *data, size_t len, void *user_data); typedef void (*gputop_on_close_cb_t)(gputop_connection_t *conn, const char *error, void *user_data); gputop_connection_t *gputop_connect(const char *host, int port, gputop_on_ready_cb_t ready_cb, gputop_on_data_cb_t data_cb, gputop_on_close_cb_t close_cb, void *user_data); void gputop_connection_send(gputop_connection_t *conn, const void *data, size_t len); void gputop_connection_close(gputop_connection_t *conn); bool gputop_connection_connected(gputop_connection_t *conn); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* __GPUTOP_NETWORK_H__ */ ================================================ FILE: lib/gputop-oa-counters.c ================================================ /* * GPU Top * * Copyright (C) 2015-2016 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define _GNU_SOURCE #ifdef EMSCRIPTEN #include #else #define EMSCRIPTEN_KEEPALIVE #endif #include #include "gputop-oa-counters.h" #ifdef GPUTOP_CLIENT #include "gputop-client-c-runtime.h" #define dbg gputop_cr_console_log #else #include "gputop-log.h" #endif uint32_t gputop_time_to_oa_exponent(struct gputop_devinfo *devinfo, uint64_t period_ns) { for (int i = 0; i < 30; i++) { uint64_t oa_period = gputop_oa_exponent_to_period_ns(devinfo, i); if (oa_period > period_ns) return MAX2(0, i - 1); } unreachable("Period out of range"); return 0; } static void gputop_u32_clock_init(struct gputop_u32_clock *clock, const struct gputop_devinfo *devinfo, uint32_t u32_start) { clock->timestamp = clock->start = gputop_timebase_scale_ns(devinfo, u32_start); clock->last_u32 = u32_start; clock->devinfo = devinfo; clock->clock_count = 0ULL; } static uint64_t gputop_u32_clock_get_time(struct gputop_u32_clock *clock) { return clock->timestamp; } static void gputop_u32_clock_progress(struct gputop_u32_clock *clock, uint32_t u32_start_timestamp, uint32_t u32_end_timestamp) { uint32_t delta = u32_end_timestamp - clock->last_u32; clock->timestamp += gputop_timebase_scale_ns(clock->devinfo, delta); clock->last_u32 = u32_end_timestamp; clock->clock_count += u32_end_timestamp - u32_start_timestamp; } static void accumulate_uint32(const uint32_t *report0, const uint32_t *report1, uint64_t *deltas) { *deltas += (uint32_t)(*report1 - *report0); } static void accumulate_uint40(int a_index, const uint32_t *report0, const uint32_t *report1, uint64_t *deltas) { const uint8_t *high_bytes0 = (uint8_t *)(report0 + 40); const uint8_t *high_bytes1 = (uint8_t *)(report1 + 40); uint64_t high0 = (uint64_t)(high_bytes0[a_index]) << 32; uint64_t high1 = (uint64_t)(high_bytes1[a_index]) << 32; uint64_t value0 = report0[a_index + 4] | high0; uint64_t value1 = report1[a_index + 4] | high1; uint64_t delta; if (value0 > value1) delta = (1ULL << 40) + value1 - value0; else delta = value1 - value0; *deltas += delta; } bool gputop_cc_oa_accumulate_reports(struct gputop_cc_oa_accumulator *accumulator, const uint8_t *report0, const uint8_t *report1) { const struct gputop_metric_set *metric_set = accumulator->metric_set; uint64_t *deltas = accumulator->deltas; const uint32_t *start = (const uint32_t *)report0; const uint32_t *end = (const uint32_t *)report1; int idx = 0; int i; assert(report0 != report1); /* technically a timestamp of zero is valid, but much more likely it * indicates a problem... */ if (start[1] == 0 || end[1] == 0) { dbg("i915_oa: spurious report with timestamp of zero\n"); return false; } if (!accumulator->clock.devinfo) gputop_u32_clock_init(&accumulator->clock, accumulator->devinfo, gputop_cc_oa_report_get_timestamp(report0)); //gputop_u32_clock_progress(&accumulator->clock, start[1]); if (!accumulator->first_timestamp) accumulator->first_timestamp = gputop_u32_clock_get_time(&accumulator->clock); switch (metric_set->perf_oa_format) { case I915_OA_FORMAT_A32u40_A4u32_B8_C8: accumulate_uint32(start + 1, end + 1, deltas + idx++); /* timestamp */ accumulate_uint32(start + 3, end + 3, deltas + idx++); /* clock */ /* 32x 40bit A counters... */ for (i = 0; i < 32; i++) accumulate_uint40(i, start, end, deltas + idx++); /* 4x 32bit A counters... */ for (i = 0; i < 4; i++) accumulate_uint32(start + 36 + i, end + 36 + i, deltas + idx++); /* 8x 32bit B counters + 8x 32bit C counters... */ for (i = 0; i < 16; i++) accumulate_uint32(start + 48 + i, end + 48 + i, deltas + idx++); break; case I915_OA_FORMAT_A45_B8_C8: accumulate_uint32(start + 1, end + 1, deltas); /* timestamp */ for (i = 0; i < 61; i++) accumulate_uint32(start + 3 + i, end + 3 + i, deltas + 1 + i); break; default: assert(0); } gputop_u32_clock_progress(&accumulator->clock, start[1], end[1]); accumulator->last_timestamp = gputop_u32_clock_get_time(&accumulator->clock); return true; } void EMSCRIPTEN_KEEPALIVE gputop_cc_oa_accumulator_clear(struct gputop_cc_oa_accumulator *accumulator) { memset(accumulator->deltas, 0, sizeof(accumulator->deltas)); accumulator->first_timestamp = 0; accumulator->last_timestamp = 0; } void gputop_cc_oa_accumulator_init(struct gputop_cc_oa_accumulator *accumulator, const struct gputop_devinfo *devinfo, const struct gputop_metric_set *metric_set, int aggregation_period, const uint8_t *first_report) { assert(accumulator); assert(metric_set); assert(metric_set->perf_oa_format); memset(accumulator, 0, sizeof(*accumulator)); accumulator->devinfo = devinfo; accumulator->metric_set = metric_set; accumulator->aggregation_period = aggregation_period; if (first_report) { gputop_u32_clock_init(&accumulator->clock, accumulator->devinfo, gputop_cc_oa_report_get_timestamp(first_report)); accumulator->first_timestamp = gputop_u32_clock_get_time(&accumulator->clock); } } ================================================ FILE: lib/gputop-oa-counters.h ================================================ /* * GPU Top * * Copyright (C) 2015-2016 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include #include #include #include #include "gputop-oa-metrics.h" #ifdef __cplusplus extern "C" { #endif #define GPUTOP_OA_INVALID_CTX_ID (0xffffffff) /* NB: the timestamps written by the OA unit are 32 bits counting in ~80 * nanosecond units (at least on Haswell) so it wraps every ~ 6 minutes, this * gputop_u32_clock api accumulates a 64bit monotonic timestamp in nanoseconds */ struct gputop_u32_clock { const struct gputop_devinfo *devinfo; uint64_t start; uint64_t timestamp; uint32_t last_u32; uint64_t clock_count; }; struct gputop_cc_oa_accumulator { const struct gputop_devinfo *devinfo; const struct gputop_metric_set *metric_set; uint64_t aggregation_period; uint64_t first_timestamp; uint64_t last_timestamp; #define MAX_RAW_OA_COUNTERS 62 uint64_t deltas[MAX_RAW_OA_COUNTERS]; struct gputop_u32_clock clock; }; void gputop_cc_oa_accumulator_init(struct gputop_cc_oa_accumulator *accumulator, const struct gputop_devinfo *devinfo, const struct gputop_metric_set *metric_set, int aggregation_period, const uint8_t *first_report); void gputop_cc_oa_accumulator_clear(struct gputop_cc_oa_accumulator *accumulator); bool gputop_cc_oa_accumulate_reports(struct gputop_cc_oa_accumulator *accumulator, const uint8_t *report0, const uint8_t *report1); static inline uint64_t gputop_time_scale_timebase(const struct gputop_devinfo *devinfo, uint64_t ns_time) { return (ns_time * devinfo->timestamp_frequency) / 1000000000ULL; } static inline uint64_t gputop_timebase_scale_ns(const struct gputop_devinfo *devinfo, uint64_t u32_time) { return (u32_time * 1000000000ULL) / devinfo->timestamp_frequency; } static inline uint64_t gputop_oa_exponent_to_period_ns(const struct gputop_devinfo *devinfo, uint32_t exponent) { return ((2ULL << exponent) * 1000000000ULL) / devinfo->timestamp_frequency; } uint32_t gputop_time_to_oa_exponent(struct gputop_devinfo *devinfo, uint64_t period_ns); static inline bool gputop_cc_oa_report_ctx_is_valid(const struct gputop_devinfo *devinfo, const uint8_t *_report) { const uint32_t *report = (const uint32_t *) _report; if (devinfo->gen < 8) { return false; /* TODO */ } else if (devinfo->gen == 8) { return report[0] & (1ul << 25); } else if (devinfo->gen > 8) { return report[0] & (1ul << 16); } return false; } static inline uint32_t gputop_cc_oa_report_get_ctx_id(const struct gputop_devinfo *devinfo, const uint8_t *report) { if (!gputop_cc_oa_report_ctx_is_valid(devinfo, report)) return GPUTOP_OA_INVALID_CTX_ID; return ((const uint32_t *) report)[2]; } static inline uint64_t gputop_cc_oa_report_get_timestamp(const uint8_t *report) { return ((uint32_t *)report)[1]; } static inline const char * gputop_cc_oa_report_get_reason(const struct gputop_devinfo *devinfo, const uint8_t *report) { const uint32_t *report32 = (const uint32_t *) report; uint32_t reason; if (devinfo->gen < 8) return "unknown (gen7)"; reason = ((report32[0] >> 19) & 0x3f); if (reason & (1<<0)) return "timer"; if (reason & (1<<1)) return "internal trigger 1"; if (reason & (1<<2)) return "internal trigger 2"; if (reason & (1<<3)) return "context switch"; if (reason & (1<<4)) return "GO 1->0 transition (enter RC6)"; if (reason & (1<<5)) return "[un]slice clock ratio change"; return "unknown"; } struct gputop_i915_perf_configuration { bool oa_reports; bool cpu_timestamps; bool gpu_timestamps; }; enum gputop_i915_perf_field { GPUTOP_I915_PERF_FIELD_OA_REPORT, GPUTOP_I915_PERF_FIELD_CPU_TIMESTAMP, GPUTOP_I915_PERF_FIELD_GPU_TIMESTAMP, }; static inline uint64_t gputop_i915_perf_record_max_size(const struct gputop_i915_perf_configuration *config) { uint64_t size = sizeof(struct drm_i915_perf_record_header); if (config->oa_reports) size += 256ULL; /* Default OA report size */ if (config->gpu_timestamps) size += sizeof(uint64_t); if (config->cpu_timestamps) size += sizeof(uint64_t); return size; } static inline const void * gputop_i915_perf_record_field(const struct gputop_i915_perf_configuration *config, const struct drm_i915_perf_record_header *header, enum gputop_i915_perf_field field) { const uint8_t *ptr = (const uint8_t *) (header + 1); if (config->gpu_timestamps) { if (field == GPUTOP_I915_PERF_FIELD_GPU_TIMESTAMP) return ptr; ptr += sizeof(uint64_t); } if (config->cpu_timestamps) { if (field == GPUTOP_I915_PERF_FIELD_CPU_TIMESTAMP) return ptr; ptr += sizeof(uint64_t); } if (config->oa_reports) { if (field == GPUTOP_I915_PERF_FIELD_OA_REPORT) return ptr; } return NULL; } static inline uint32_t gputop_i915_perf_record_timestamp(const struct gputop_i915_perf_configuration *config, const struct drm_i915_perf_record_header *header) { if (header->type != DRM_I915_PERF_RECORD_SAMPLE) return 0; return gputop_cc_oa_report_get_timestamp( (const uint8_t *) gputop_i915_perf_record_field(config, header, GPUTOP_I915_PERF_FIELD_OA_REPORT)); } static inline const char * gputop_i915_perf_record_reason(const struct gputop_i915_perf_configuration *config, const struct gputop_devinfo *devinfo, const struct drm_i915_perf_record_header *header) { switch (header->type) { case DRM_I915_PERF_RECORD_SAMPLE: return gputop_cc_oa_report_get_reason(devinfo, (const uint8_t *) gputop_i915_perf_record_field(config, header, GPUTOP_I915_PERF_FIELD_OA_REPORT)); case DRM_I915_PERF_RECORD_OA_REPORT_LOST: return "report lost"; case DRM_I915_PERF_RECORD_OA_BUFFER_LOST: return "buffer lost"; default: return "unknown/error"; } } #ifdef __cplusplus } #endif ================================================ FILE: lib/gputop-oa-metrics.c ================================================ /* * GPU Top * * Copyright (C) 2018 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "gputop-oa-metrics.h" #include "gputop-gens-metrics.h" #include #include "util/hash_table.h" #include "util/ralloc.h" struct gputop_gen * gputop_gen_for_devinfo(const struct gen_device_info *devinfo) { struct gputop_devinfo gputop_devinfo = {}; if (devinfo->is_haswell) return gputop_oa_get_metrics_hsw(&gputop_devinfo); if (devinfo->is_broadwell) return gputop_oa_get_metrics_bdw(&gputop_devinfo); if (devinfo->is_cherryview) return gputop_oa_get_metrics_chv(&gputop_devinfo); if (devinfo->is_skylake) { switch (devinfo->gt) { case 2: return gputop_oa_get_metrics_sklgt2(&gputop_devinfo); case 3: return gputop_oa_get_metrics_sklgt3(&gputop_devinfo); case 4: return gputop_oa_get_metrics_sklgt4(&gputop_devinfo); default: return NULL; } } if (devinfo->is_broxton) return gputop_oa_get_metrics_bxt(&gputop_devinfo); if (devinfo->is_kabylake) { switch (devinfo->gt) { case 2: return gputop_oa_get_metrics_kblgt2(&gputop_devinfo); case 3: return gputop_oa_get_metrics_kblgt3(&gputop_devinfo); default: return NULL; } } if (devinfo->is_geminilake) return gputop_oa_get_metrics_glk(&gputop_devinfo); if (devinfo->is_coffeelake) { switch (devinfo->gt) { case 2: return gputop_oa_get_metrics_cflgt2(&gputop_devinfo); case 3: return gputop_oa_get_metrics_cflgt3(&gputop_devinfo); default: return NULL; } } if (devinfo->is_cannonlake) return gputop_oa_get_metrics_cnl(&gputop_devinfo); if (devinfo->gen == 11) return gputop_oa_get_metrics_icl(&gputop_devinfo); if (devinfo->gen == 12) return gputop_oa_get_metrics_tgl(&gputop_devinfo); return NULL; } static struct gputop_counter_group * gputop_counter_group_new(struct gputop_gen *gen, struct gputop_counter_group *parent, const char *name) { struct gputop_counter_group *group = ralloc(gen, struct gputop_counter_group); group->name = ralloc_strdup(group, name); list_inithead(&group->counters); list_inithead(&group->groups); if (parent) list_addtail(&group->link, &parent->groups); else list_inithead(&group->link); return group; } struct gputop_gen * gputop_gen_new(void) { struct gputop_gen *gen = ralloc(NULL, struct gputop_gen); gen->root_group = gputop_counter_group_new(gen, NULL, ""); list_inithead(&gen->metric_sets); gen->metric_sets_map = _mesa_hash_table_create(gen, _mesa_hash_string, _mesa_key_string_equal); return gen; } void gputop_gen_add_counter(struct gputop_gen *gen, struct gputop_metric_set_counter *counter, const char *group_path) { const char *group_path_end = group_path + strlen(group_path); struct gputop_counter_group *group = gen->root_group, *child_group = NULL; const char *name = group_path; while (name < group_path_end) { const char *name_end = strstr(name, "/"); char group_name[128] = { 0, }; if (!name_end) name_end = group_path_end; memcpy(group_name, name, name_end - name); child_group = NULL; list_for_each_entry(struct gputop_counter_group, iter_group, &group->groups, link) { if (!strcmp(iter_group->name, group_name)) { child_group = iter_group; break; } } if (!child_group) child_group = gputop_counter_group_new(gen, group, group_name); name = name_end + 1; group = child_group; } list_addtail(&counter->link, &child_group->counters); } void gputop_gen_add_metric_set(struct gputop_gen *gen, struct gputop_metric_set *metric_set) { list_addtail(&metric_set->link, &gen->metric_sets); _mesa_hash_table_insert(gen->metric_sets_map, metric_set->hw_config_guid, metric_set); } ================================================ FILE: lib/gputop-oa-metrics.h ================================================ /* * GPU Top * * Copyright (C) 2015-2016 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include #include #include "dev/gen_device_info.h" #include "util/hash_table.h" #include "util/list.h" #ifdef __cplusplus extern "C" { #endif struct gputop_devtopology { uint32_t max_slices; uint32_t max_subslices; uint32_t max_eus_per_subslice; uint32_t n_threads_per_eu; /* Max values should be enough for a while. */ uint8_t slices_mask[4]; uint8_t subslices_mask[16]; uint8_t eus_mask[256]; uint32_t engines[5]; }; struct gputop_devinfo { char devname[20]; char prettyname[100]; uint32_t devid; uint32_t gen; uint32_t revision; uint64_t timestamp_frequency; uint64_t gt_min_freq; uint64_t gt_max_freq; /* Always false for gputop, we don't have the additional snapshots of * register values, only the OA reports. */ bool query_mode; bool has_dynamic_configs; struct gputop_devtopology topology; /* The following fields are prepared for equations from the XML files. * Their values are build up from the topology fields. */ uint64_t n_eus; uint64_t n_eu_slices; uint64_t n_eu_sub_slices; uint64_t subslice_mask; uint64_t slice_mask; uint64_t eu_threads_count; }; typedef enum { GPUTOP_PERFQUERY_COUNTER_DATA_UINT64, GPUTOP_PERFQUERY_COUNTER_DATA_UINT32, GPUTOP_PERFQUERY_COUNTER_DATA_DOUBLE, GPUTOP_PERFQUERY_COUNTER_DATA_FLOAT, GPUTOP_PERFQUERY_COUNTER_DATA_BOOL32, } gputop_counter_data_type_t; typedef enum { GPUTOP_PERFQUERY_COUNTER_RAW, GPUTOP_PERFQUERY_COUNTER_DURATION_RAW, GPUTOP_PERFQUERY_COUNTER_DURATION_NORM, GPUTOP_PERFQUERY_COUNTER_EVENT, GPUTOP_PERFQUERY_COUNTER_THROUGHPUT, GPUTOP_PERFQUERY_COUNTER_TIMESTAMP, } gputop_counter_type_t; typedef enum { /* size */ GPUTOP_PERFQUERY_COUNTER_UNITS_BYTES, /* frequency */ GPUTOP_PERFQUERY_COUNTER_UNITS_HZ, /* time */ GPUTOP_PERFQUERY_COUNTER_UNITS_NS, GPUTOP_PERFQUERY_COUNTER_UNITS_US, /**/ GPUTOP_PERFQUERY_COUNTER_UNITS_PIXELS, GPUTOP_PERFQUERY_COUNTER_UNITS_TEXELS, GPUTOP_PERFQUERY_COUNTER_UNITS_THREADS, GPUTOP_PERFQUERY_COUNTER_UNITS_PERCENT, /* events */ GPUTOP_PERFQUERY_COUNTER_UNITS_MESSAGES, GPUTOP_PERFQUERY_COUNTER_UNITS_NUMBER, GPUTOP_PERFQUERY_COUNTER_UNITS_CYCLES, GPUTOP_PERFQUERY_COUNTER_UNITS_EVENTS, GPUTOP_PERFQUERY_COUNTER_UNITS_UTILIZATION, /**/ GPUTOP_PERFQUERY_COUNTER_UNITS_EU_SENDS_TO_L3_CACHE_LINES, GPUTOP_PERFQUERY_COUNTER_UNITS_EU_ATOMIC_REQUESTS_TO_L3_CACHE_LINES, GPUTOP_PERFQUERY_COUNTER_UNITS_EU_REQUESTS_TO_L3_CACHE_LINES, GPUTOP_PERFQUERY_COUNTER_UNITS_EU_BYTES_PER_L3_CACHE_LINE, GPUTOP_PERFQUERY_COUNTER_UNITS_MAX } gputop_counter_units_t; #define OAREPORT_REASON_MASK 0x3f #define OAREPORT_REASON_SHIFT 19 #define OAREPORT_REASON_TIMER (1<<0) #define OAREPORT_REASON_CTX_SWITCH (1<<3) struct gputop_metric_set; struct gputop_metric_set_counter { const struct gputop_metric_set *metric_set; const char *name; const char *symbol_name; const char *desc; gputop_counter_type_t type; gputop_counter_data_type_t data_type; gputop_counter_units_t units; union { uint64_t (*max_uint64)(const struct gputop_devinfo *devinfo, const struct gputop_metric_set *metric_set, uint64_t *deltas); double (*max_float)(const struct gputop_devinfo *devinfo, const struct gputop_metric_set *metric_set, uint64_t *deltas); }; union { uint64_t (*oa_counter_read_uint64)(const struct gputop_devinfo *devinfo, const struct gputop_metric_set *metric_set, uint64_t *deltas); double (*oa_counter_read_float)(const struct gputop_devinfo *devinfo, const struct gputop_metric_set *metric_set, uint64_t *deltas); }; struct list_head link; /* list from gputop_counter_group.counters */ }; struct gputop_register_prog { uint32_t reg; uint32_t val; }; struct gputop_metric_set { const char *name; const char *symbol_name; const char *hw_config_guid; struct gputop_metric_set_counter *counters; int n_counters; uint64_t perf_oa_metrics_set; int perf_oa_format; int perf_raw_size; /* For indexing into accumulator->deltas[] ... */ int gpu_time_offset; int gpu_clock_offset; int a_offset; int b_offset; int c_offset; struct gputop_register_prog *b_counter_regs; uint32_t n_b_counter_regs; struct gputop_register_prog *mux_regs; uint32_t n_mux_regs; struct gputop_register_prog *flex_regs; uint32_t n_flex_regs; struct list_head link; }; struct gputop_counter_group { const char *name; struct list_head counters; struct list_head groups; struct list_head link; /* list from gputop_counter_group.groups */ }; struct gputop_gen { const char *name; struct gputop_counter_group *root_group; struct list_head metric_sets; struct hash_table *metric_sets_map; }; /* Free with ralloc_free() */ struct gputop_gen *gputop_gen_for_devinfo(const struct gen_device_info *devinfo); struct gputop_gen *gputop_gen_new(void); void gputop_gen_add_counter(struct gputop_gen *gen, struct gputop_metric_set_counter *counter, const char *group); void gputop_gen_add_metric_set(struct gputop_gen *gen, struct gputop_metric_set *metric_set); #ifdef __cplusplus } #endif ================================================ FILE: lib/gputop-util.h ================================================ /* * GPU Top * * Copyright (C) 2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include #include #include #include #include #include #include #include #include #include #ifndef MIN #define MIN(x, y) (((x) < (y)) ? (x) : (y)) #endif #ifndef MAX #define MAX(a, b) (((a) > (b)) ? (a) : (b)) #endif #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x))) #endif #ifndef ALIGN #define ALIGN(x, align) (((x) % (align)) == 0 ? (x) : ((x) + ((align) - (x) % (align)))) #endif static inline void * xmalloc(size_t size) { void *ret = malloc(size); if (!ret) exit(1); return ret; } static inline void * xmalloc0(size_t size) { void *ret = malloc(size); if (!ret) exit(1); memset(ret, 0, size); return ret; } static inline void * xrealloc(void *ptr, size_t size) { void *ret = realloc(ptr, size); if (!ret) exit(1); return ret; } struct array { size_t elem_size; int len; size_t size; union { void *data; uint8_t *bytes; }; }; static inline struct array * array_new(size_t elem_size, int alloc_len) { struct array *array = (struct array *) xmalloc(sizeof(struct array)); array->elem_size = elem_size; array->len = 0; array->size = elem_size * alloc_len; array->data = xmalloc(array->size); return array; } static inline void array_free(struct array *array) { free(array->data); free(array); } static inline void array_set_len(struct array *array, int len) { size_t needed = len * array->elem_size; array->len = len; if (array->size >= needed) return; array->size = MAX(needed, array->size * 1.7); array->data = xrealloc(array->data, array->size); } static inline void array_remove_fast(struct array *array, int idx) { uint8_t *elem; uint8_t *last; array->len--; if (idx == array->len) return; elem = array->bytes + idx * array->elem_size; last = array->bytes + array->len * array->elem_size; memcpy(elem, last, array->elem_size); } static inline void array_append(struct array *array, void *data) { void *dst; array_set_len(array, array->len + 1); dst = array->bytes + array->elem_size * (array->len - 1); memcpy(dst, data, array->elem_size); } #define array_value_at(ARRAY, TYPE, IDX) *(((TYPE *)(ARRAY)->data) + IDX) static inline void string_rstrip(char *string) { int len = strlen(string); while (isspace(string[len - 1])) { string[len - 1] = '\0'; len--; } } ================================================ FILE: lib/meson.build ================================================ gputop_client_src = [ 'gputop-client-context.c', 'gputop-oa-counters.c', 'gputop-oa-metrics.c', ] gputop_client_generated_src = [] gputop_client_generated_src += custom_target( 'proto-files', input : [join_paths(meson.current_source_dir(), '../data/gputop.proto')], output : ['gputop.pb-c.c', 'gputop.pb-c.h'], command : [protoc_c, '--c_out=@OUTDIR@', '-I' + join_paths(meson.current_source_dir(), '../data'), join_paths(meson.current_source_dir(), '../data/gputop.proto')]) hardware = [ 'hsw', 'bdw', 'chv', 'sklgt2', 'sklgt3', 'sklgt4', 'kblgt2', 'kblgt3', 'cflgt2', 'cflgt3', 'bxt', 'glk', 'cnl', 'icl', 'lkf', 'tgl', ] gen_xml_files = [] foreach hw : hardware gen_xml_files += '../data/oa-@0@.xml'.format(hw) endforeach gputop_client_generated_src += custom_target( 'gputop-gens-metrics', input : gen_xml_files, output : [ 'gputop-gens-metrics.c', 'gputop-gens-metrics.h' ], command : [ find_program('../scripts/gputop-oa-codegen.py'), '--code', '@OUTPUT0@', '--header', '@OUTPUT1@', '@INPUT@', ]) gputop_client_generated_src += custom_target( 'tracepoint-parser', output: 'tracepoint_format.leg.h', input: 'tracepoint_format.leg', command: [leg, '-P', '-o', '@OUTPUT@', '@INPUT@']) gputop_client_inc = include_directories('.') gputop_client = static_library('gputop_client', gputop_client_src + gputop_client_generated_src, dependencies : [mesa_dep, protobuf_c_dep], include_directories : gputop_client_inc) gputop_client_dep = declare_dependency(link_with : gputop_client, dependencies : [mesa_dep, protobuf_c_dep], sources : gputop_client_generated_src, include_directories : gputop_client_inc) ================================================ FILE: lib/tracepoint_format.leg ================================================ TracepointFormat = 'name' ':' Space n:PropertyName EndLine { free(n.string); } 'ID' ':' Space Number EndLine 'format' ':' EndLine Field+ 'print fmt' ':' .* !. Field = Space (Property ';' Space)+ EndLine { yy->ctx.tp->n_fields++; } | EndLine Property = 'offset' ':' v:Number { yy->ctx.tp->fields[yy->ctx.tp->n_fields].offset = v.integer; } | 'size' ':' v:Number { yy->ctx.tp->fields[yy->ctx.tp->n_fields].size = v.integer; } | 'signed' ':' v:Number { yy->ctx.tp->fields[yy->ctx.tp->n_fields].is_signed = v.integer != 0; } | 'field' ':' v:PropertyValue { snprintf(yy->ctx.tp->fields[yy->ctx.tp->n_fields].name, sizeof(yy->ctx.tp->fields[yy->ctx.tp->n_fields].name), "%s", strrchr(v.string, ' ') + 1); free(v.string); } | n:PropertyName ':' v:PropertyValue { free(n.string); free(v.string); } PropertyName = < [A-Za-z0-9_]+ > { $$.string = strdup(yytext); } PropertyValue = < [^;]+ > { $$.string = strdup(yytext); } Number = < [0-9]+ > { $$.integer = atoi(yytext); } EndLine = [\n] Space = [ \t]* ================================================ FILE: mesa/include/c11/threads.h ================================================ /* * C11 emulation library * * (C) Copyright yohhoy 2012. * Distributed under the Boost Software License, Version 1.0. * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare [[derivative work]]s of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef EMULATED_THREADS_H_INCLUDED_ #define EMULATED_THREADS_H_INCLUDED_ #include #ifndef TIME_UTC #define TIME_UTC 1 #endif #include "c99_compat.h" /* for `inline` */ /*---------------------------- types ----------------------------*/ typedef void (*tss_dtor_t)(void*); typedef int (*thrd_start_t)(void*); /*-------------------- enumeration constants --------------------*/ enum { mtx_plain = 0, mtx_try = 1, mtx_timed = 2, mtx_recursive = 4 }; enum { thrd_success = 0, // succeeded thrd_timeout, // timeout thrd_error, // failed thrd_busy, // resource busy thrd_nomem // out of memory }; /*-------------------------- functions --------------------------*/ #if defined(_WIN32) && !defined(__CYGWIN__) #include "threads_win32.h" #elif defined(HAVE_PTHREAD) #include "threads_posix.h" #else #error Not supported on this platform. #endif #endif /* EMULATED_THREADS_H_INCLUDED_ */ ================================================ FILE: mesa/include/c11/threads_posix.h ================================================ /* * C11 emulation library * * (C) Copyright yohhoy 2012. * Distributed under the Boost Software License, Version 1.0. * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare [[derivative work]]s of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include #ifndef assert #include #endif #include #include #include #include #include /* for intptr_t */ /* Configuration macro: EMULATED_THREADS_USE_NATIVE_TIMEDLOCK Use pthread_mutex_timedlock() for `mtx_timedlock()' Otherwise use mtx_trylock() + *busy loop* emulation. */ #if !defined(__CYGWIN__) && !defined(__APPLE__) && !defined(__NetBSD__) #define EMULATED_THREADS_USE_NATIVE_TIMEDLOCK #endif #include /*---------------------------- macros ----------------------------*/ #define ONCE_FLAG_INIT PTHREAD_ONCE_INIT #ifdef INIT_ONCE_STATIC_INIT #define TSS_DTOR_ITERATIONS PTHREAD_DESTRUCTOR_ITERATIONS #else #define TSS_DTOR_ITERATIONS 1 // assume TSS dtor MAY be called at least once. #endif // FIXME: temporary non-standard hack to ease transition #define _MTX_INITIALIZER_NP PTHREAD_MUTEX_INITIALIZER /*---------------------------- types ----------------------------*/ typedef pthread_cond_t cnd_t; typedef pthread_t thrd_t; typedef pthread_key_t tss_t; typedef pthread_mutex_t mtx_t; typedef pthread_once_t once_flag; /* Implementation limits: - Conditionally emulation for "mutex with timeout" (see EMULATED_THREADS_USE_NATIVE_TIMEDLOCK macro) */ struct impl_thrd_param { thrd_start_t func; void *arg; }; static inline void * impl_thrd_routine(void *p) { struct impl_thrd_param pack = *((struct impl_thrd_param *)p); free(p); return (void*)(intptr_t)pack.func(pack.arg); } /*--------------- 7.25.2 Initialization functions ---------------*/ // 7.25.2.1 static inline void call_once(once_flag *flag, void (*func)(void)) { pthread_once(flag, func); } /*------------- 7.25.3 Condition variable functions -------------*/ // 7.25.3.1 static inline int cnd_broadcast(cnd_t *cond) { assert(cond != NULL); return (pthread_cond_broadcast(cond) == 0) ? thrd_success : thrd_error; } // 7.25.3.2 static inline void cnd_destroy(cnd_t *cond) { assert(cond); pthread_cond_destroy(cond); } // 7.25.3.3 static inline int cnd_init(cnd_t *cond) { assert(cond != NULL); return (pthread_cond_init(cond, NULL) == 0) ? thrd_success : thrd_error; } // 7.25.3.4 static inline int cnd_signal(cnd_t *cond) { assert(cond != NULL); return (pthread_cond_signal(cond) == 0) ? thrd_success : thrd_error; } // 7.25.3.5 static inline int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *abs_time) { int rt; assert(mtx != NULL); assert(cond != NULL); assert(abs_time != NULL); rt = pthread_cond_timedwait(cond, mtx, abs_time); if (rt == ETIMEDOUT) return thrd_busy; return (rt == 0) ? thrd_success : thrd_error; } // 7.25.3.6 static inline int cnd_wait(cnd_t *cond, mtx_t *mtx) { assert(mtx != NULL); assert(cond != NULL); return (pthread_cond_wait(cond, mtx) == 0) ? thrd_success : thrd_error; } /*-------------------- 7.25.4 Mutex functions --------------------*/ // 7.25.4.1 static inline void mtx_destroy(mtx_t *mtx) { assert(mtx != NULL); pthread_mutex_destroy(mtx); } /* * XXX: Workaround when building with -O0 and without pthreads link. * * In such cases constant folding and dead code elimination won't be * available, thus the compiler will always add the pthread_mutexattr* * functions into the binary. As we try to link, we'll fail as the * symbols are unresolved. * * Ideally we'll enable the optimisations locally, yet that does not * seem to work. * * So the alternative workaround is to annotate the symbols as weak. * Thus the linker will be happy and things don't clash when building * with -O1 or greater. */ #if defined(HAVE_FUNC_ATTRIBUTE_WEAK) && !defined(__CYGWIN__) __attribute__((weak)) int pthread_mutexattr_init(pthread_mutexattr_t *attr); __attribute__((weak)) int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type); __attribute__((weak)) int pthread_mutexattr_destroy(pthread_mutexattr_t *attr); #endif // 7.25.4.2 static inline int mtx_init(mtx_t *mtx, int type) { pthread_mutexattr_t attr; assert(mtx != NULL); if (type != mtx_plain && type != mtx_timed && type != mtx_try && type != (mtx_plain|mtx_recursive) && type != (mtx_timed|mtx_recursive) && type != (mtx_try|mtx_recursive)) return thrd_error; if ((type & mtx_recursive) == 0) { pthread_mutex_init(mtx, NULL); return thrd_success; } pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(mtx, &attr); pthread_mutexattr_destroy(&attr); return thrd_success; } // 7.25.4.3 static inline int mtx_lock(mtx_t *mtx) { assert(mtx != NULL); return (pthread_mutex_lock(mtx) == 0) ? thrd_success : thrd_error; } static inline int mtx_trylock(mtx_t *mtx); static inline void thrd_yield(void); // 7.25.4.4 static inline int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) { assert(mtx != NULL); assert(ts != NULL); { #ifdef EMULATED_THREADS_USE_NATIVE_TIMEDLOCK int rt; rt = pthread_mutex_timedlock(mtx, ts); if (rt == 0) return thrd_success; return (rt == ETIMEDOUT) ? thrd_busy : thrd_error; #else time_t expire = time(NULL); expire += ts->tv_sec; while (mtx_trylock(mtx) != thrd_success) { time_t now = time(NULL); if (expire < now) return thrd_busy; // busy loop! thrd_yield(); } return thrd_success; #endif } } // 7.25.4.5 static inline int mtx_trylock(mtx_t *mtx) { assert(mtx != NULL); return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy; } // 7.25.4.6 static inline int mtx_unlock(mtx_t *mtx) { assert(mtx != NULL); return (pthread_mutex_unlock(mtx) == 0) ? thrd_success : thrd_error; } /*------------------- 7.25.5 Thread functions -------------------*/ // 7.25.5.1 static inline int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) { struct impl_thrd_param *pack; assert(thr != NULL); pack = (struct impl_thrd_param *)malloc(sizeof(struct impl_thrd_param)); if (!pack) return thrd_nomem; pack->func = func; pack->arg = arg; if (pthread_create(thr, NULL, impl_thrd_routine, pack) != 0) { free(pack); return thrd_error; } return thrd_success; } // 7.25.5.2 static inline thrd_t thrd_current(void) { return pthread_self(); } // 7.25.5.3 static inline int thrd_detach(thrd_t thr) { return (pthread_detach(thr) == 0) ? thrd_success : thrd_error; } // 7.25.5.4 static inline int thrd_equal(thrd_t thr0, thrd_t thr1) { return pthread_equal(thr0, thr1); } // 7.25.5.5 static inline void thrd_exit(int res) { pthread_exit((void*)(intptr_t)res); } // 7.25.5.6 static inline int thrd_join(thrd_t thr, int *res) { void *code; if (pthread_join(thr, &code) != 0) return thrd_error; if (res) *res = (int)(intptr_t)code; return thrd_success; } // 7.25.5.7 static inline void thrd_sleep(const struct timespec *time_point, struct timespec *remaining) { assert(time_point != NULL); nanosleep(time_point, remaining); } // 7.25.5.8 static inline void thrd_yield(void) { sched_yield(); } /*----------- 7.25.6 Thread-specific storage functions -----------*/ // 7.25.6.1 static inline int tss_create(tss_t *key, tss_dtor_t dtor) { assert(key != NULL); return (pthread_key_create(key, dtor) == 0) ? thrd_success : thrd_error; } // 7.25.6.2 static inline void tss_delete(tss_t key) { pthread_key_delete(key); } // 7.25.6.3 static inline void * tss_get(tss_t key) { return pthread_getspecific(key); } // 7.25.6.4 static inline int tss_set(tss_t key, void *val) { return (pthread_setspecific(key, val) == 0) ? thrd_success : thrd_error; } /*-------------------- 7.25.7 Time functions --------------------*/ // 7.25.6.1 #ifndef HAVE_TIMESPEC_GET static inline int timespec_get(struct timespec *ts, int base) { if (!ts) return 0; if (base == TIME_UTC) { clock_gettime(CLOCK_REALTIME, ts); return base; } return 0; } #endif ================================================ FILE: mesa/include/c11/threads_win32.h ================================================ /* * C11 emulation library * * (C) Copyright yohhoy 2012. * Distributed under the Boost Software License, Version 1.0. * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare [[derivative work]]s of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef assert #include #endif #include #include #include // MSVCRT #include /* Configuration macro: EMULATED_THREADS_USE_NATIVE_CALL_ONCE Use native WindowsAPI one-time initialization function. (requires WinVista or later) Otherwise emulate by mtx_trylock() + *busy loop* for WinXP. EMULATED_THREADS_USE_NATIVE_CV Use native WindowsAPI condition variable object. (requires WinVista or later) Otherwise use emulated implementation for WinXP. EMULATED_THREADS_TSS_DTOR_SLOTNUM Max registerable TSS dtor number. */ // XXX: Retain XP compatability #if 0 #if _WIN32_WINNT >= 0x0600 // Prefer native WindowsAPI on newer environment. #if !defined(__MINGW32__) #define EMULATED_THREADS_USE_NATIVE_CALL_ONCE #endif #define EMULATED_THREADS_USE_NATIVE_CV #endif #endif #define EMULATED_THREADS_TSS_DTOR_SLOTNUM 64 // see TLS_MINIMUM_AVAILABLE #include // check configuration #if defined(EMULATED_THREADS_USE_NATIVE_CALL_ONCE) && (_WIN32_WINNT < 0x0600) #error EMULATED_THREADS_USE_NATIVE_CALL_ONCE requires _WIN32_WINNT>=0x0600 #endif #if defined(EMULATED_THREADS_USE_NATIVE_CV) && (_WIN32_WINNT < 0x0600) #error EMULATED_THREADS_USE_NATIVE_CV requires _WIN32_WINNT>=0x0600 #endif /* Visual Studio 2015 and later */ #ifdef _MSC_VER #define HAVE_TIMESPEC_GET #endif /*---------------------------- macros ----------------------------*/ #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE #define ONCE_FLAG_INIT INIT_ONCE_STATIC_INIT #else #define ONCE_FLAG_INIT {0} #endif #define TSS_DTOR_ITERATIONS 1 // FIXME: temporary non-standard hack to ease transition #define _MTX_INITIALIZER_NP {(PCRITICAL_SECTION_DEBUG)-1, -1, 0, 0, 0, 0} /*---------------------------- types ----------------------------*/ typedef struct cnd_t { #ifdef EMULATED_THREADS_USE_NATIVE_CV CONDITION_VARIABLE condvar; #else int blocked; int gone; int to_unblock; HANDLE sem_queue; HANDLE sem_gate; CRITICAL_SECTION monitor; #endif } cnd_t; typedef HANDLE thrd_t; typedef DWORD tss_t; typedef CRITICAL_SECTION mtx_t; #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE typedef INIT_ONCE once_flag; #else typedef struct once_flag_t { volatile LONG status; } once_flag; #endif static inline void * tss_get(tss_t key); static inline void thrd_yield(void); static inline int mtx_trylock(mtx_t *mtx); static inline int mtx_lock(mtx_t *mtx); static inline int mtx_unlock(mtx_t *mtx); /* Implementation limits: - Conditionally emulation for "Initialization functions" (see EMULATED_THREADS_USE_NATIVE_CALL_ONCE macro) - Emulated `mtx_timelock()' with mtx_trylock() + *busy loop* */ static void impl_tss_dtor_invoke(void); // forward decl. struct impl_thrd_param { thrd_start_t func; void *arg; }; static unsigned __stdcall impl_thrd_routine(void *p) { struct impl_thrd_param pack; int code; memcpy(&pack, p, sizeof(struct impl_thrd_param)); free(p); code = pack.func(pack.arg); impl_tss_dtor_invoke(); return (unsigned)code; } static DWORD impl_timespec2msec(const struct timespec *ts) { return (DWORD)((ts->tv_sec * 1000U) + (ts->tv_nsec / 1000000L)); } #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE struct impl_call_once_param { void (*func)(void); }; static BOOL CALLBACK impl_call_once_callback(PINIT_ONCE InitOnce, PVOID Parameter, PVOID *Context) { struct impl_call_once_param *param = (struct impl_call_once_param*)Parameter; (param->func)(); ((void)InitOnce); ((void)Context); // suppress warning return TRUE; } #endif // ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE #ifndef EMULATED_THREADS_USE_NATIVE_CV /* Note: The implementation of condition variable is ported from Boost.Interprocess See http://www.boost.org/boost/interprocess/sync/windows/condition.hpp */ static void impl_cond_do_signal(cnd_t *cond, int broadcast) { int nsignal = 0; EnterCriticalSection(&cond->monitor); if (cond->to_unblock != 0) { if (cond->blocked == 0) { LeaveCriticalSection(&cond->monitor); return; } if (broadcast) { cond->to_unblock += nsignal = cond->blocked; cond->blocked = 0; } else { nsignal = 1; cond->to_unblock++; cond->blocked--; } } else if (cond->blocked > cond->gone) { WaitForSingleObject(cond->sem_gate, INFINITE); if (cond->gone != 0) { cond->blocked -= cond->gone; cond->gone = 0; } if (broadcast) { nsignal = cond->to_unblock = cond->blocked; cond->blocked = 0; } else { nsignal = cond->to_unblock = 1; cond->blocked--; } } LeaveCriticalSection(&cond->monitor); if (0 < nsignal) ReleaseSemaphore(cond->sem_queue, nsignal, NULL); } static int impl_cond_do_wait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) { int nleft = 0; int ngone = 0; int timeout = 0; DWORD w; WaitForSingleObject(cond->sem_gate, INFINITE); cond->blocked++; ReleaseSemaphore(cond->sem_gate, 1, NULL); mtx_unlock(mtx); w = WaitForSingleObject(cond->sem_queue, ts ? impl_timespec2msec(ts) : INFINITE); timeout = (w == WAIT_TIMEOUT); EnterCriticalSection(&cond->monitor); if ((nleft = cond->to_unblock) != 0) { if (timeout) { if (cond->blocked != 0) { cond->blocked--; } else { cond->gone++; } } if (--cond->to_unblock == 0) { if (cond->blocked != 0) { ReleaseSemaphore(cond->sem_gate, 1, NULL); nleft = 0; } else if ((ngone = cond->gone) != 0) { cond->gone = 0; } } } else if (++cond->gone == INT_MAX/2) { WaitForSingleObject(cond->sem_gate, INFINITE); cond->blocked -= cond->gone; ReleaseSemaphore(cond->sem_gate, 1, NULL); cond->gone = 0; } LeaveCriticalSection(&cond->monitor); if (nleft == 1) { while (ngone--) WaitForSingleObject(cond->sem_queue, INFINITE); ReleaseSemaphore(cond->sem_gate, 1, NULL); } mtx_lock(mtx); return timeout ? thrd_busy : thrd_success; } #endif // ifndef EMULATED_THREADS_USE_NATIVE_CV static struct impl_tss_dtor_entry { tss_t key; tss_dtor_t dtor; } impl_tss_dtor_tbl[EMULATED_THREADS_TSS_DTOR_SLOTNUM]; static int impl_tss_dtor_register(tss_t key, tss_dtor_t dtor) { int i; for (i = 0; i < EMULATED_THREADS_TSS_DTOR_SLOTNUM; i++) { if (!impl_tss_dtor_tbl[i].dtor) break; } if (i == EMULATED_THREADS_TSS_DTOR_SLOTNUM) return 1; impl_tss_dtor_tbl[i].key = key; impl_tss_dtor_tbl[i].dtor = dtor; return 0; } static void impl_tss_dtor_invoke() { int i; for (i = 0; i < EMULATED_THREADS_TSS_DTOR_SLOTNUM; i++) { if (impl_tss_dtor_tbl[i].dtor) { void* val = tss_get(impl_tss_dtor_tbl[i].key); if (val) (impl_tss_dtor_tbl[i].dtor)(val); } } } /*--------------- 7.25.2 Initialization functions ---------------*/ // 7.25.2.1 static inline void call_once(once_flag *flag, void (*func)(void)) { assert(flag && func); #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE { struct impl_call_once_param param; param.func = func; InitOnceExecuteOnce(flag, impl_call_once_callback, (PVOID)¶m, NULL); } #else if (InterlockedCompareExchange(&flag->status, 1, 0) == 0) { (func)(); InterlockedExchange(&flag->status, 2); } else { while (flag->status == 1) { // busy loop! thrd_yield(); } } #endif } /*------------- 7.25.3 Condition variable functions -------------*/ // 7.25.3.1 static inline int cnd_broadcast(cnd_t *cond) { if (!cond) return thrd_error; #ifdef EMULATED_THREADS_USE_NATIVE_CV WakeAllConditionVariable(&cond->condvar); #else impl_cond_do_signal(cond, 1); #endif return thrd_success; } // 7.25.3.2 static inline void cnd_destroy(cnd_t *cond) { assert(cond); #ifdef EMULATED_THREADS_USE_NATIVE_CV // do nothing #else CloseHandle(cond->sem_queue); CloseHandle(cond->sem_gate); DeleteCriticalSection(&cond->monitor); #endif } // 7.25.3.3 static inline int cnd_init(cnd_t *cond) { if (!cond) return thrd_error; #ifdef EMULATED_THREADS_USE_NATIVE_CV InitializeConditionVariable(&cond->condvar); #else cond->blocked = 0; cond->gone = 0; cond->to_unblock = 0; cond->sem_queue = CreateSemaphore(NULL, 0, LONG_MAX, NULL); cond->sem_gate = CreateSemaphore(NULL, 1, 1, NULL); InitializeCriticalSection(&cond->monitor); #endif return thrd_success; } // 7.25.3.4 static inline int cnd_signal(cnd_t *cond) { if (!cond) return thrd_error; #ifdef EMULATED_THREADS_USE_NATIVE_CV WakeConditionVariable(&cond->condvar); #else impl_cond_do_signal(cond, 0); #endif return thrd_success; } // 7.25.3.5 static inline int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *abs_time) { if (!cond || !mtx || !abs_time) return thrd_error; #ifdef EMULATED_THREADS_USE_NATIVE_CV if (SleepConditionVariableCS(&cond->condvar, mtx, impl_timespec2msec(abs_time))) return thrd_success; return (GetLastError() == ERROR_TIMEOUT) ? thrd_busy : thrd_error; #else return impl_cond_do_wait(cond, mtx, abs_time); #endif } // 7.25.3.6 static inline int cnd_wait(cnd_t *cond, mtx_t *mtx) { if (!cond || !mtx) return thrd_error; #ifdef EMULATED_THREADS_USE_NATIVE_CV SleepConditionVariableCS(&cond->condvar, mtx, INFINITE); #else impl_cond_do_wait(cond, mtx, NULL); #endif return thrd_success; } /*-------------------- 7.25.4 Mutex functions --------------------*/ // 7.25.4.1 static inline void mtx_destroy(mtx_t *mtx) { assert(mtx); DeleteCriticalSection(mtx); } // 7.25.4.2 static inline int mtx_init(mtx_t *mtx, int type) { if (!mtx) return thrd_error; if (type != mtx_plain && type != mtx_timed && type != mtx_try && type != (mtx_plain|mtx_recursive) && type != (mtx_timed|mtx_recursive) && type != (mtx_try|mtx_recursive)) return thrd_error; InitializeCriticalSection(mtx); return thrd_success; } // 7.25.4.3 static inline int mtx_lock(mtx_t *mtx) { if (!mtx) return thrd_error; EnterCriticalSection(mtx); return thrd_success; } // 7.25.4.4 static inline int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) { time_t expire, now; if (!mtx || !ts) return thrd_error; expire = time(NULL); expire += ts->tv_sec; while (mtx_trylock(mtx) != thrd_success) { now = time(NULL); if (expire < now) return thrd_busy; // busy loop! thrd_yield(); } return thrd_success; } // 7.25.4.5 static inline int mtx_trylock(mtx_t *mtx) { if (!mtx) return thrd_error; return TryEnterCriticalSection(mtx) ? thrd_success : thrd_busy; } // 7.25.4.6 static inline int mtx_unlock(mtx_t *mtx) { if (!mtx) return thrd_error; LeaveCriticalSection(mtx); return thrd_success; } /*------------------- 7.25.5 Thread functions -------------------*/ // 7.25.5.1 static inline int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) { struct impl_thrd_param *pack; uintptr_t handle; if (!thr) return thrd_error; pack = (struct impl_thrd_param *)malloc(sizeof(struct impl_thrd_param)); if (!pack) return thrd_nomem; pack->func = func; pack->arg = arg; handle = _beginthreadex(NULL, 0, impl_thrd_routine, pack, 0, NULL); if (handle == 0) { if (errno == EAGAIN || errno == EACCES) return thrd_nomem; return thrd_error; } *thr = (thrd_t)handle; return thrd_success; } #if 0 // 7.25.5.2 static inline thrd_t thrd_current(void) { HANDLE hCurrentThread; BOOL bRet; /* GetCurrentThread() returns a pseudo-handle, which we need * to pass to DuplicateHandle(). Only the resulting handle can be used * from other threads. * * Note that neither handle can be compared to the one by thread_create. * Only the thread IDs - as returned by GetThreadId() and GetCurrentThreadId() * can be compared directly. * * Other potential solutions would be: * - define thrd_t as a thread Ids, but this would mean we'd need to OpenThread for many operations * - use malloc'ed memory for thrd_t. This would imply using TLS for current thread. * * Neither is particularly nice. * * Life would be much easier if C11 threads had different abstractions for * threads and thread IDs, just like C++11 threads does... */ bRet = DuplicateHandle(GetCurrentProcess(), // source process (pseudo) handle GetCurrentThread(), // source (pseudo) handle GetCurrentProcess(), // target process &hCurrentThread, // target handle 0, FALSE, DUPLICATE_SAME_ACCESS); assert(bRet); if (!bRet) { hCurrentThread = GetCurrentThread(); } return hCurrentThread; } #endif // 7.25.5.3 static inline int thrd_detach(thrd_t thr) { CloseHandle(thr); return thrd_success; } // 7.25.5.4 static inline int thrd_equal(thrd_t thr0, thrd_t thr1) { return GetThreadId(thr0) == GetThreadId(thr1); } // 7.25.5.5 static inline void thrd_exit(int res) { impl_tss_dtor_invoke(); _endthreadex((unsigned)res); } // 7.25.5.6 static inline int thrd_join(thrd_t thr, int *res) { DWORD w, code; w = WaitForSingleObject(thr, INFINITE); if (w != WAIT_OBJECT_0) return thrd_error; if (res) { if (!GetExitCodeThread(thr, &code)) { CloseHandle(thr); return thrd_error; } *res = (int)code; } CloseHandle(thr); return thrd_success; } // 7.25.5.7 static inline void thrd_sleep(const struct timespec *time_point, struct timespec *remaining) { assert(time_point); assert(!remaining); /* not implemented */ Sleep(impl_timespec2msec(time_point)); } // 7.25.5.8 static inline void thrd_yield(void) { SwitchToThread(); } /*----------- 7.25.6 Thread-specific storage functions -----------*/ // 7.25.6.1 static inline int tss_create(tss_t *key, tss_dtor_t dtor) { if (!key) return thrd_error; *key = TlsAlloc(); if (dtor) { if (impl_tss_dtor_register(*key, dtor)) { TlsFree(*key); return thrd_error; } } return (*key != 0xFFFFFFFF) ? thrd_success : thrd_error; } // 7.25.6.2 static inline void tss_delete(tss_t key) { TlsFree(key); } // 7.25.6.3 static inline void * tss_get(tss_t key) { return TlsGetValue(key); } // 7.25.6.4 static inline int tss_set(tss_t key, void *val) { return TlsSetValue(key, val) ? thrd_success : thrd_error; } /*-------------------- 7.25.7 Time functions --------------------*/ // 7.25.6.1 #ifndef HAVE_TIMESPEC_GET static inline int timespec_get(struct timespec *ts, int base) { if (!ts) return 0; if (base == TIME_UTC) { ts->tv_sec = time(NULL); ts->tv_nsec = 0; return base; } return 0; } #endif ================================================ FILE: mesa/include/c99_alloca.h ================================================ /************************************************************************** * * Copyright 2015 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #ifndef _C99_ALLOCA_H_ #define _C99_ALLOCA_H_ #if defined(_MSC_VER) # include # define alloca _alloca #elif defined(__sun) || defined(__CYGWIN__) # include #else /* !defined(_MSC_VER) */ # include #endif /* !defined(_MSC_VER) */ #endif ================================================ FILE: mesa/include/c99_compat.h ================================================ /************************************************************************** * * Copyright 2007-2013 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #include "no_extern_c.h" #ifndef _C99_COMPAT_H_ #define _C99_COMPAT_H_ /* * MSVC hacks. */ #if defined(_MSC_VER) # if _MSC_VER < 1900 # error "Microsoft Visual Studio 2015 or higher required" # endif /* * Visual Studio will complain if we define the `inline` keyword, but * actually it only supports the keyword on C++. * * To avoid this the _ALLOW_KEYWORD_MACROS must be set. */ # if !defined(_ALLOW_KEYWORD_MACROS) # define _ALLOW_KEYWORD_MACROS # endif /* * XXX: MSVC has a `__restrict` keyword, but it also has a * `__declspec(restrict)` modifier, so it is impossible to define a * `restrict` macro without interfering with the latter. Furthermore the * MSVC standard library uses __declspec(restrict) under the _CRTRESTRICT * macro. For now resolve this issue by redefining _CRTRESTRICT, but going * forward we should probably should stop using restrict, especially * considering that our code does not obbey strict aliasing rules any way. */ # include # undef _CRTRESTRICT # define _CRTRESTRICT #endif /* * C99 inline keyword */ #ifndef inline # ifdef __cplusplus /* C++ supports inline keyword */ # elif defined(__GNUC__) # define inline __inline__ # elif defined(_MSC_VER) # define inline __inline # elif defined(__ICL) # define inline __inline # elif defined(__INTEL_COMPILER) /* Intel compiler supports inline keyword */ # elif defined(__WATCOMC__) && (__WATCOMC__ >= 1100) # define inline __inline # elif (__STDC_VERSION__ >= 199901L) /* C99 supports inline keyword */ # else # define inline # endif #endif /* * C99 restrict keyword * * See also: * - http://cellperformance.beyond3d.com/articles/2006/05/demystifying-the-restrict-keyword.html */ #ifndef restrict # if (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) /* C99 */ # elif defined(__GNUC__) # define restrict __restrict__ # elif defined(_MSC_VER) # define restrict __restrict # else # define restrict /* */ # endif #endif /* * C99 __func__ macro */ #ifndef __func__ # if (__STDC_VERSION__ >= 199901L) /* C99 */ # elif defined(__GNUC__) # define __func__ __FUNCTION__ # elif defined(_MSC_VER) # define __func__ __FUNCTION__ # else # define __func__ "" # endif #endif /* Simple test case for debugging */ #if 0 static inline const char * test_c99_compat_h(const void * restrict a, const void * restrict b) { return __func__; } #endif /* Fallback definitions, for scons which doesn't auto-detect these things. */ #ifdef HAVE_SCONS # ifndef _WIN32 # define HAVE_PTHREAD # define HAVE_POSIX_MEMALIGN # endif # ifdef __GNUC__ # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) # error "GCC version 4.2 or higher required" # endif /* https://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Other-Builtins.html */ # define HAVE___BUILTIN_CLZ 1 # define HAVE___BUILTIN_CLZLL 1 # define HAVE___BUILTIN_CTZ 1 # define HAVE___BUILTIN_EXPECT 1 # define HAVE___BUILTIN_FFS 1 # define HAVE___BUILTIN_FFSLL 1 # define HAVE___BUILTIN_POPCOUNT 1 # define HAVE___BUILTIN_POPCOUNTLL 1 /* https://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Function-Attributes.html */ # define HAVE_FUNC_ATTRIBUTE_FLATTEN 1 # define HAVE_FUNC_ATTRIBUTE_UNUSED 1 # define HAVE_FUNC_ATTRIBUTE_FORMAT 1 # define HAVE_FUNC_ATTRIBUTE_PACKED 1 # define HAVE_FUNC_ATTRIBUTE_ALIAS 1 # define HAVE_FUNC_ATTRIBUTE_NORETURN 1 # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) /* https://gcc.gnu.org/onlinedocs/gcc-4.3.6/gcc/Other-Builtins.html */ # define HAVE___BUILTIN_BSWAP32 1 # define HAVE___BUILTIN_BSWAP64 1 # endif # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) # define HAVE___BUILTIN_UNREACHABLE 1 # endif # endif /* __GNUC__ */ #endif /* HAVE_SCONS */ #endif /* _C99_COMPAT_H_ */ ================================================ FILE: mesa/include/c99_math.h ================================================ /************************************************************************** * * Copyright 2007-2015 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ /** * Wrapper for math.h which makes sure we have definitions of all the c99 * functions. */ #ifndef _C99_MATH_H_ #define _C99_MATH_H_ #include #include "c99_compat.h" /* This is to ensure that we get M_PI, etc. definitions */ #if defined(_MSC_VER) && !defined(_USE_MATH_DEFINES) #error _USE_MATH_DEFINES define required when building with MSVC #endif #if !defined(_MSC_VER) && \ __STDC_VERSION__ < 199901L && \ (!defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 600) && \ !defined(__cplusplus) static inline long int lrint(double d) { long int rounded = (long int)(d + 0.5); if (d - floor(d) == 0.5) { if (rounded % 2 != 0) rounded += (d > 0) ? -1 : 1; } return rounded; } static inline long int lrintf(float f) { long int rounded = (long int)(f + 0.5f); if (f - floorf(f) == 0.5f) { if (rounded % 2 != 0) rounded += (f > 0) ? -1 : 1; } return rounded; } static inline long long int llrint(double d) { long long int rounded = (long long int)(d + 0.5); if (d - floor(d) == 0.5) { if (rounded % 2 != 0) rounded += (d > 0) ? -1 : 1; } return rounded; } static inline long long int llrintf(float f) { long long int rounded = (long long int)(f + 0.5f); if (f - floorf(f) == 0.5f) { if (rounded % 2 != 0) rounded += (f > 0) ? -1 : 1; } return rounded; } static inline float exp2f(float f) { return powf(2.0f, f); } static inline double exp2(double d) { return pow(2.0, d); } #endif /* C99 */ /* * signbit() is a macro on Linux. Not available on Windows. */ #ifndef signbit #define signbit(x) ((x) < 0.0f) #endif #ifndef M_PI #define M_PI (3.14159265358979323846) #endif #ifndef M_E #define M_E (2.7182818284590452354) #endif #ifndef M_LOG2E #define M_LOG2E (1.4426950408889634074) #endif #ifndef FLT_MAX_EXP #define FLT_MAX_EXP 128 #endif #if defined(fpclassify) /* ISO C99 says that fpclassify is a macro. Assume that any implementation * of fpclassify, whether it's in a C99 compiler or not, will be a macro. */ #elif defined(__cplusplus) /* For C++, fpclassify() should be defined in */ #elif defined(_MSC_VER) /* Not required on VS2013 and above. Oddly, the fpclassify() function * doesn't exist in such a form on MSVC. This is an implementation using * slightly different lower-level Windows functions. */ #include static inline enum {FP_NAN, FP_INFINITE, FP_ZERO, FP_SUBNORMAL, FP_NORMAL} fpclassify(double x) { switch(_fpclass(x)) { case _FPCLASS_SNAN: /* signaling NaN */ case _FPCLASS_QNAN: /* quiet NaN */ return FP_NAN; case _FPCLASS_NINF: /* negative infinity */ case _FPCLASS_PINF: /* positive infinity */ return FP_INFINITE; case _FPCLASS_NN: /* negative normal */ case _FPCLASS_PN: /* positive normal */ return FP_NORMAL; case _FPCLASS_ND: /* negative denormalized */ case _FPCLASS_PD: /* positive denormalized */ return FP_SUBNORMAL; case _FPCLASS_NZ: /* negative zero */ case _FPCLASS_PZ: /* positive zero */ return FP_ZERO; default: /* Should never get here; but if we do, this will guarantee * that the pattern is not treated like a number. */ return FP_NAN; } } #else #error "Need to include or define an fpclassify function" #endif /* Since C++11, the following functions are part of the std namespace. Their C * counteparts should still exist in the global namespace, however cmath * undefines those functions, which in glibc 2.23, are defined as macros rather * than functions as in glibc 2.22. */ #if __cplusplus >= 201103L && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 23)) #include using std::fpclassify; using std::isfinite; using std::isinf; using std::isnan; using std::isnormal; using std::signbit; using std::isgreater; using std::isgreaterequal; using std::isless; using std::islessequal; using std::islessgreater; using std::isunordered; #endif #endif /* #define _C99_MATH_H_ */ ================================================ FILE: mesa/include/drm-uapi/README ================================================ This directory contains a copy of the installed kernel headers required by several drivers to communicate with the kernel. Whenever one of those driver needs new definitions for new kernel APIs, these files should be updated. These files in master should only be updated once the changes have landed in the drm-next tree. You can copy files installed after running this from the kernel repository, at version the drivers require : $ make headers_install INSTALL_HDR_PATH=/path/to/install The last update was done at the following kernel commit : commit f1b4a9217efd61d0b84c6dc404596c8519ff6f59 Merge: 400e91347e1d f3a36d469621 Author: Dave Airlie Date: Tue Oct 22 15:04:00 2019 +1000 Merge tag 'du-next-20191016' of git://linuxtv.org/pinchartl/media into drm-next ================================================ FILE: mesa/include/drm-uapi/drm.h ================================================ /** * \file drm.h * Header for the Direct Rendering Manager * * \author Rickard E. (Rik) Faith * * \par Acknowledgments: * Dec 1999, Richard Henderson , move to generic \c cmpxchg. */ /* * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas. * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _DRM_H_ #define _DRM_H_ #if defined(__linux__) #include #include typedef unsigned int drm_handle_t; #else /* One of the BSDs */ #include #if defined(EMSCRIPTEN) #include #else #include #endif #include typedef int8_t __s8; typedef uint8_t __u8; typedef int16_t __s16; typedef uint16_t __u16; typedef int32_t __s32; typedef uint32_t __u32; typedef int64_t __s64; typedef uint64_t __u64; typedef size_t __kernel_size_t; typedef unsigned long drm_handle_t; #endif #if defined(__cplusplus) extern "C" { #endif #define DRM_NAME "drm" /**< Name in kernel, /dev, and /proc */ #define DRM_MIN_ORDER 5 /**< At least 2^5 bytes = 32 bytes */ #define DRM_MAX_ORDER 22 /**< Up to 2^22 bytes = 4MB */ #define DRM_RAM_PERCENT 10 /**< How much system ram can we lock? */ #define _DRM_LOCK_HELD 0x80000000U /**< Hardware lock is held */ #define _DRM_LOCK_CONT 0x40000000U /**< Hardware lock is contended */ #define _DRM_LOCK_IS_HELD(lock) ((lock) & _DRM_LOCK_HELD) #define _DRM_LOCK_IS_CONT(lock) ((lock) & _DRM_LOCK_CONT) #define _DRM_LOCKING_CONTEXT(lock) ((lock) & ~(_DRM_LOCK_HELD|_DRM_LOCK_CONT)) typedef unsigned int drm_context_t; typedef unsigned int drm_drawable_t; typedef unsigned int drm_magic_t; /** * Cliprect. * * \warning: If you change this structure, make sure you change * XF86DRIClipRectRec in the server as well * * \note KW: Actually it's illegal to change either for * backwards-compatibility reasons. */ struct drm_clip_rect { unsigned short x1; unsigned short y1; unsigned short x2; unsigned short y2; }; /** * Drawable information. */ struct drm_drawable_info { unsigned int num_rects; struct drm_clip_rect *rects; }; /** * Texture region, */ struct drm_tex_region { unsigned char next; unsigned char prev; unsigned char in_use; unsigned char padding; unsigned int age; }; /** * Hardware lock. * * The lock structure is a simple cache-line aligned integer. To avoid * processor bus contention on a multiprocessor system, there should not be any * other data stored in the same cache line. */ struct drm_hw_lock { __volatile__ unsigned int lock; /**< lock variable */ char padding[60]; /**< Pad to cache line */ }; /** * DRM_IOCTL_VERSION ioctl argument type. * * \sa drmGetVersion(). */ struct drm_version { int version_major; /**< Major version */ int version_minor; /**< Minor version */ int version_patchlevel; /**< Patch level */ __kernel_size_t name_len; /**< Length of name buffer */ char *name; /**< Name of driver */ __kernel_size_t date_len; /**< Length of date buffer */ char *date; /**< User-space buffer to hold date */ __kernel_size_t desc_len; /**< Length of desc buffer */ char *desc; /**< User-space buffer to hold desc */ }; /** * DRM_IOCTL_GET_UNIQUE ioctl argument type. * * \sa drmGetBusid() and drmSetBusId(). */ struct drm_unique { __kernel_size_t unique_len; /**< Length of unique */ char *unique; /**< Unique name for driver instantiation */ }; struct drm_list { int count; /**< Length of user-space structures */ struct drm_version *version; }; struct drm_block { int unused; }; /** * DRM_IOCTL_CONTROL ioctl argument type. * * \sa drmCtlInstHandler() and drmCtlUninstHandler(). */ struct drm_control { enum { DRM_ADD_COMMAND, DRM_RM_COMMAND, DRM_INST_HANDLER, DRM_UNINST_HANDLER } func; int irq; }; /** * Type of memory to map. */ enum drm_map_type { _DRM_FRAME_BUFFER = 0, /**< WC (no caching), no core dump */ _DRM_REGISTERS = 1, /**< no caching, no core dump */ _DRM_SHM = 2, /**< shared, cached */ _DRM_AGP = 3, /**< AGP/GART */ _DRM_SCATTER_GATHER = 4, /**< Scatter/gather memory for PCI DMA */ _DRM_CONSISTENT = 5 /**< Consistent memory for PCI DMA */ }; /** * Memory mapping flags. */ enum drm_map_flags { _DRM_RESTRICTED = 0x01, /**< Cannot be mapped to user-virtual */ _DRM_READ_ONLY = 0x02, _DRM_LOCKED = 0x04, /**< shared, cached, locked */ _DRM_KERNEL = 0x08, /**< kernel requires access */ _DRM_WRITE_COMBINING = 0x10, /**< use write-combining if available */ _DRM_CONTAINS_LOCK = 0x20, /**< SHM page that contains lock */ _DRM_REMOVABLE = 0x40, /**< Removable mapping */ _DRM_DRIVER = 0x80 /**< Managed by driver */ }; struct drm_ctx_priv_map { unsigned int ctx_id; /**< Context requesting private mapping */ void *handle; /**< Handle of map */ }; /** * DRM_IOCTL_GET_MAP, DRM_IOCTL_ADD_MAP and DRM_IOCTL_RM_MAP ioctls * argument type. * * \sa drmAddMap(). */ struct drm_map { unsigned long offset; /**< Requested physical address (0 for SAREA)*/ unsigned long size; /**< Requested physical size (bytes) */ enum drm_map_type type; /**< Type of memory to map */ enum drm_map_flags flags; /**< Flags */ void *handle; /**< User-space: "Handle" to pass to mmap() */ /**< Kernel-space: kernel-virtual address */ int mtrr; /**< MTRR slot used */ /* Private data */ }; /** * DRM_IOCTL_GET_CLIENT ioctl argument type. */ struct drm_client { int idx; /**< Which client desired? */ int auth; /**< Is client authenticated? */ unsigned long pid; /**< Process ID */ unsigned long uid; /**< User ID */ unsigned long magic; /**< Magic */ unsigned long iocs; /**< Ioctl count */ }; enum drm_stat_type { _DRM_STAT_LOCK, _DRM_STAT_OPENS, _DRM_STAT_CLOSES, _DRM_STAT_IOCTLS, _DRM_STAT_LOCKS, _DRM_STAT_UNLOCKS, _DRM_STAT_VALUE, /**< Generic value */ _DRM_STAT_BYTE, /**< Generic byte counter (1024bytes/K) */ _DRM_STAT_COUNT, /**< Generic non-byte counter (1000/k) */ _DRM_STAT_IRQ, /**< IRQ */ _DRM_STAT_PRIMARY, /**< Primary DMA bytes */ _DRM_STAT_SECONDARY, /**< Secondary DMA bytes */ _DRM_STAT_DMA, /**< DMA */ _DRM_STAT_SPECIAL, /**< Special DMA (e.g., priority or polled) */ _DRM_STAT_MISSED /**< Missed DMA opportunity */ /* Add to the *END* of the list */ }; /** * DRM_IOCTL_GET_STATS ioctl argument type. */ struct drm_stats { unsigned long count; struct { unsigned long value; enum drm_stat_type type; } data[15]; }; /** * Hardware locking flags. */ enum drm_lock_flags { _DRM_LOCK_READY = 0x01, /**< Wait until hardware is ready for DMA */ _DRM_LOCK_QUIESCENT = 0x02, /**< Wait until hardware quiescent */ _DRM_LOCK_FLUSH = 0x04, /**< Flush this context's DMA queue first */ _DRM_LOCK_FLUSH_ALL = 0x08, /**< Flush all DMA queues first */ /* These *HALT* flags aren't supported yet -- they will be used to support the full-screen DGA-like mode. */ _DRM_HALT_ALL_QUEUES = 0x10, /**< Halt all current and future queues */ _DRM_HALT_CUR_QUEUES = 0x20 /**< Halt all current queues */ }; /** * DRM_IOCTL_LOCK, DRM_IOCTL_UNLOCK and DRM_IOCTL_FINISH ioctl argument type. * * \sa drmGetLock() and drmUnlock(). */ struct drm_lock { int context; enum drm_lock_flags flags; }; /** * DMA flags * * \warning * These values \e must match xf86drm.h. * * \sa drm_dma. */ enum drm_dma_flags { /* Flags for DMA buffer dispatch */ _DRM_DMA_BLOCK = 0x01, /**< * Block until buffer dispatched. * * \note The buffer may not yet have * been processed by the hardware -- * getting a hardware lock with the * hardware quiescent will ensure * that the buffer has been * processed. */ _DRM_DMA_WHILE_LOCKED = 0x02, /**< Dispatch while lock held */ _DRM_DMA_PRIORITY = 0x04, /**< High priority dispatch */ /* Flags for DMA buffer request */ _DRM_DMA_WAIT = 0x10, /**< Wait for free buffers */ _DRM_DMA_SMALLER_OK = 0x20, /**< Smaller-than-requested buffers OK */ _DRM_DMA_LARGER_OK = 0x40 /**< Larger-than-requested buffers OK */ }; /** * DRM_IOCTL_ADD_BUFS and DRM_IOCTL_MARK_BUFS ioctl argument type. * * \sa drmAddBufs(). */ struct drm_buf_desc { int count; /**< Number of buffers of this size */ int size; /**< Size in bytes */ int low_mark; /**< Low water mark */ int high_mark; /**< High water mark */ enum { _DRM_PAGE_ALIGN = 0x01, /**< Align on page boundaries for DMA */ _DRM_AGP_BUFFER = 0x02, /**< Buffer is in AGP space */ _DRM_SG_BUFFER = 0x04, /**< Scatter/gather memory buffer */ _DRM_FB_BUFFER = 0x08, /**< Buffer is in frame buffer */ _DRM_PCI_BUFFER_RO = 0x10 /**< Map PCI DMA buffer read-only */ } flags; unsigned long agp_start; /**< * Start address of where the AGP buffers are * in the AGP aperture */ }; /** * DRM_IOCTL_INFO_BUFS ioctl argument type. */ struct drm_buf_info { int count; /**< Entries in list */ struct drm_buf_desc *list; }; /** * DRM_IOCTL_FREE_BUFS ioctl argument type. */ struct drm_buf_free { int count; int *list; }; /** * Buffer information * * \sa drm_buf_map. */ struct drm_buf_pub { int idx; /**< Index into the master buffer list */ int total; /**< Buffer size */ int used; /**< Amount of buffer in use (for DMA) */ void *address; /**< Address of buffer */ }; /** * DRM_IOCTL_MAP_BUFS ioctl argument type. */ struct drm_buf_map { int count; /**< Length of the buffer list */ #ifdef __cplusplus void *virt; #else void *virtual; /**< Mmap'd area in user-virtual */ #endif struct drm_buf_pub *list; /**< Buffer information */ }; /** * DRM_IOCTL_DMA ioctl argument type. * * Indices here refer to the offset into the buffer list in drm_buf_get. * * \sa drmDMA(). */ struct drm_dma { int context; /**< Context handle */ int send_count; /**< Number of buffers to send */ int *send_indices; /**< List of handles to buffers */ int *send_sizes; /**< Lengths of data to send */ enum drm_dma_flags flags; /**< Flags */ int request_count; /**< Number of buffers requested */ int request_size; /**< Desired size for buffers */ int *request_indices; /**< Buffer information */ int *request_sizes; int granted_count; /**< Number of buffers granted */ }; enum drm_ctx_flags { _DRM_CONTEXT_PRESERVED = 0x01, _DRM_CONTEXT_2DONLY = 0x02 }; /** * DRM_IOCTL_ADD_CTX ioctl argument type. * * \sa drmCreateContext() and drmDestroyContext(). */ struct drm_ctx { drm_context_t handle; enum drm_ctx_flags flags; }; /** * DRM_IOCTL_RES_CTX ioctl argument type. */ struct drm_ctx_res { int count; struct drm_ctx *contexts; }; /** * DRM_IOCTL_ADD_DRAW and DRM_IOCTL_RM_DRAW ioctl argument type. */ struct drm_draw { drm_drawable_t handle; }; /** * DRM_IOCTL_UPDATE_DRAW ioctl argument type. */ typedef enum { DRM_DRAWABLE_CLIPRECTS } drm_drawable_info_type_t; struct drm_update_draw { drm_drawable_t handle; unsigned int type; unsigned int num; unsigned long long data; }; /** * DRM_IOCTL_GET_MAGIC and DRM_IOCTL_AUTH_MAGIC ioctl argument type. */ struct drm_auth { drm_magic_t magic; }; /** * DRM_IOCTL_IRQ_BUSID ioctl argument type. * * \sa drmGetInterruptFromBusID(). */ struct drm_irq_busid { int irq; /**< IRQ number */ int busnum; /**< bus number */ int devnum; /**< device number */ int funcnum; /**< function number */ }; enum drm_vblank_seq_type { _DRM_VBLANK_ABSOLUTE = 0x0, /**< Wait for specific vblank sequence number */ _DRM_VBLANK_RELATIVE = 0x1, /**< Wait for given number of vblanks */ /* bits 1-6 are reserved for high crtcs */ _DRM_VBLANK_HIGH_CRTC_MASK = 0x0000003e, _DRM_VBLANK_EVENT = 0x4000000, /**< Send event instead of blocking */ _DRM_VBLANK_FLIP = 0x8000000, /**< Scheduled buffer swap should flip */ _DRM_VBLANK_NEXTONMISS = 0x10000000, /**< If missed, wait for next vblank */ _DRM_VBLANK_SECONDARY = 0x20000000, /**< Secondary display controller */ _DRM_VBLANK_SIGNAL = 0x40000000 /**< Send signal instead of blocking, unsupported */ }; #define _DRM_VBLANK_HIGH_CRTC_SHIFT 1 #define _DRM_VBLANK_TYPES_MASK (_DRM_VBLANK_ABSOLUTE | _DRM_VBLANK_RELATIVE) #define _DRM_VBLANK_FLAGS_MASK (_DRM_VBLANK_EVENT | _DRM_VBLANK_SIGNAL | \ _DRM_VBLANK_SECONDARY | _DRM_VBLANK_NEXTONMISS) struct drm_wait_vblank_request { enum drm_vblank_seq_type type; unsigned int sequence; unsigned long signal; }; struct drm_wait_vblank_reply { enum drm_vblank_seq_type type; unsigned int sequence; long tval_sec; long tval_usec; }; /** * DRM_IOCTL_WAIT_VBLANK ioctl argument type. * * \sa drmWaitVBlank(). */ union drm_wait_vblank { struct drm_wait_vblank_request request; struct drm_wait_vblank_reply reply; }; #define _DRM_PRE_MODESET 1 #define _DRM_POST_MODESET 2 /** * DRM_IOCTL_MODESET_CTL ioctl argument type * * \sa drmModesetCtl(). */ struct drm_modeset_ctl { __u32 crtc; __u32 cmd; }; /** * DRM_IOCTL_AGP_ENABLE ioctl argument type. * * \sa drmAgpEnable(). */ struct drm_agp_mode { unsigned long mode; /**< AGP mode */ }; /** * DRM_IOCTL_AGP_ALLOC and DRM_IOCTL_AGP_FREE ioctls argument type. * * \sa drmAgpAlloc() and drmAgpFree(). */ struct drm_agp_buffer { unsigned long size; /**< In bytes -- will round to page boundary */ unsigned long handle; /**< Used for binding / unbinding */ unsigned long type; /**< Type of memory to allocate */ unsigned long physical; /**< Physical used by i810 */ }; /** * DRM_IOCTL_AGP_BIND and DRM_IOCTL_AGP_UNBIND ioctls argument type. * * \sa drmAgpBind() and drmAgpUnbind(). */ struct drm_agp_binding { unsigned long handle; /**< From drm_agp_buffer */ unsigned long offset; /**< In bytes -- will round to page boundary */ }; /** * DRM_IOCTL_AGP_INFO ioctl argument type. * * \sa drmAgpVersionMajor(), drmAgpVersionMinor(), drmAgpGetMode(), * drmAgpBase(), drmAgpSize(), drmAgpMemoryUsed(), drmAgpMemoryAvail(), * drmAgpVendorId() and drmAgpDeviceId(). */ struct drm_agp_info { int agp_version_major; int agp_version_minor; unsigned long mode; unsigned long aperture_base; /* physical address */ unsigned long aperture_size; /* bytes */ unsigned long memory_allowed; /* bytes */ unsigned long memory_used; /* PCI information */ unsigned short id_vendor; unsigned short id_device; }; /** * DRM_IOCTL_SG_ALLOC ioctl argument type. */ struct drm_scatter_gather { unsigned long size; /**< In bytes -- will round to page boundary */ unsigned long handle; /**< Used for mapping / unmapping */ }; /** * DRM_IOCTL_SET_VERSION ioctl argument type. */ struct drm_set_version { int drm_di_major; int drm_di_minor; int drm_dd_major; int drm_dd_minor; }; /** DRM_IOCTL_GEM_CLOSE ioctl argument type */ struct drm_gem_close { /** Handle of the object to be closed. */ __u32 handle; __u32 pad; }; /** DRM_IOCTL_GEM_FLINK ioctl argument type */ struct drm_gem_flink { /** Handle for the object being named */ __u32 handle; /** Returned global name */ __u32 name; }; /** DRM_IOCTL_GEM_OPEN ioctl argument type */ struct drm_gem_open { /** Name of object being opened */ __u32 name; /** Returned handle for the object */ __u32 handle; /** Returned size of the object */ __u64 size; }; #define DRM_CAP_DUMB_BUFFER 0x1 #define DRM_CAP_VBLANK_HIGH_CRTC 0x2 #define DRM_CAP_DUMB_PREFERRED_DEPTH 0x3 #define DRM_CAP_DUMB_PREFER_SHADOW 0x4 #define DRM_CAP_PRIME 0x5 #define DRM_PRIME_CAP_IMPORT 0x1 #define DRM_PRIME_CAP_EXPORT 0x2 #define DRM_CAP_TIMESTAMP_MONOTONIC 0x6 #define DRM_CAP_ASYNC_PAGE_FLIP 0x7 /* * The CURSOR_WIDTH and CURSOR_HEIGHT capabilities return a valid widthxheight * combination for the hardware cursor. The intention is that a hardware * agnostic userspace can query a cursor plane size to use. * * Note that the cross-driver contract is to merely return a valid size; * drivers are free to attach another meaning on top, eg. i915 returns the * maximum plane size. */ #define DRM_CAP_CURSOR_WIDTH 0x8 #define DRM_CAP_CURSOR_HEIGHT 0x9 #define DRM_CAP_ADDFB2_MODIFIERS 0x10 #define DRM_CAP_PAGE_FLIP_TARGET 0x11 #define DRM_CAP_CRTC_IN_VBLANK_EVENT 0x12 #define DRM_CAP_SYNCOBJ 0x13 #define DRM_CAP_SYNCOBJ_TIMELINE 0x14 /** DRM_IOCTL_GET_CAP ioctl argument type */ struct drm_get_cap { __u64 capability; __u64 value; }; /** * DRM_CLIENT_CAP_STEREO_3D * * if set to 1, the DRM core will expose the stereo 3D capabilities of the * monitor by advertising the supported 3D layouts in the flags of struct * drm_mode_modeinfo. */ #define DRM_CLIENT_CAP_STEREO_3D 1 /** * DRM_CLIENT_CAP_UNIVERSAL_PLANES * * If set to 1, the DRM core will expose all planes (overlay, primary, and * cursor) to userspace. */ #define DRM_CLIENT_CAP_UNIVERSAL_PLANES 2 /** * DRM_CLIENT_CAP_ATOMIC * * If set to 1, the DRM core will expose atomic properties to userspace */ #define DRM_CLIENT_CAP_ATOMIC 3 /** * DRM_CLIENT_CAP_ASPECT_RATIO * * If set to 1, the DRM core will provide aspect ratio information in modes. */ #define DRM_CLIENT_CAP_ASPECT_RATIO 4 /** * DRM_CLIENT_CAP_WRITEBACK_CONNECTORS * * If set to 1, the DRM core will expose special connectors to be used for * writing back to memory the scene setup in the commit. Depends on client * also supporting DRM_CLIENT_CAP_ATOMIC */ #define DRM_CLIENT_CAP_WRITEBACK_CONNECTORS 5 /** DRM_IOCTL_SET_CLIENT_CAP ioctl argument type */ struct drm_set_client_cap { __u64 capability; __u64 value; }; #define DRM_RDWR O_RDWR #define DRM_CLOEXEC O_CLOEXEC struct drm_prime_handle { __u32 handle; /** Flags.. only applicable for handle->fd */ __u32 flags; /** Returned dmabuf file descriptor */ __s32 fd; }; struct drm_syncobj_create { __u32 handle; #define DRM_SYNCOBJ_CREATE_SIGNALED (1 << 0) __u32 flags; }; struct drm_syncobj_destroy { __u32 handle; __u32 pad; }; #define DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE (1 << 0) #define DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE (1 << 0) struct drm_syncobj_handle { __u32 handle; __u32 flags; __s32 fd; __u32 pad; }; struct drm_syncobj_transfer { __u32 src_handle; __u32 dst_handle; __u64 src_point; __u64 dst_point; __u32 flags; __u32 pad; }; #define DRM_SYNCOBJ_WAIT_FLAGS_WAIT_ALL (1 << 0) #define DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT (1 << 1) #define DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE (1 << 2) /* wait for time point to become available */ struct drm_syncobj_wait { __u64 handles; /* absolute timeout */ __s64 timeout_nsec; __u32 count_handles; __u32 flags; __u32 first_signaled; /* only valid when not waiting all */ __u32 pad; }; struct drm_syncobj_timeline_wait { __u64 handles; /* wait on specific timeline point for every handles*/ __u64 points; /* absolute timeout */ __s64 timeout_nsec; __u32 count_handles; __u32 flags; __u32 first_signaled; /* only valid when not waiting all */ __u32 pad; }; struct drm_syncobj_array { __u64 handles; __u32 count_handles; __u32 pad; }; struct drm_syncobj_timeline_array { __u64 handles; __u64 points; __u32 count_handles; __u32 pad; }; /* Query current scanout sequence number */ struct drm_crtc_get_sequence { __u32 crtc_id; /* requested crtc_id */ __u32 active; /* return: crtc output is active */ __u64 sequence; /* return: most recent vblank sequence */ __s64 sequence_ns; /* return: most recent time of first pixel out */ }; /* Queue event to be delivered at specified sequence. Time stamp marks * when the first pixel of the refresh cycle leaves the display engine * for the display */ #define DRM_CRTC_SEQUENCE_RELATIVE 0x00000001 /* sequence is relative to current */ #define DRM_CRTC_SEQUENCE_NEXT_ON_MISS 0x00000002 /* Use next sequence if we've missed */ struct drm_crtc_queue_sequence { __u32 crtc_id; __u32 flags; __u64 sequence; /* on input, target sequence. on output, actual sequence */ __u64 user_data; /* user data passed to event */ }; #if defined(__cplusplus) } #endif #include "drm_mode.h" #if defined(__cplusplus) extern "C" { #endif #define DRM_IOCTL_BASE 'd' #define DRM_IO(nr) _IO(DRM_IOCTL_BASE,nr) #define DRM_IOR(nr,type) _IOR(DRM_IOCTL_BASE,nr,type) #define DRM_IOW(nr,type) _IOW(DRM_IOCTL_BASE,nr,type) #define DRM_IOWR(nr,type) _IOWR(DRM_IOCTL_BASE,nr,type) #define DRM_IOCTL_VERSION DRM_IOWR(0x00, struct drm_version) #define DRM_IOCTL_GET_UNIQUE DRM_IOWR(0x01, struct drm_unique) #define DRM_IOCTL_GET_MAGIC DRM_IOR( 0x02, struct drm_auth) #define DRM_IOCTL_IRQ_BUSID DRM_IOWR(0x03, struct drm_irq_busid) #define DRM_IOCTL_GET_MAP DRM_IOWR(0x04, struct drm_map) #define DRM_IOCTL_GET_CLIENT DRM_IOWR(0x05, struct drm_client) #define DRM_IOCTL_GET_STATS DRM_IOR( 0x06, struct drm_stats) #define DRM_IOCTL_SET_VERSION DRM_IOWR(0x07, struct drm_set_version) #define DRM_IOCTL_MODESET_CTL DRM_IOW(0x08, struct drm_modeset_ctl) #define DRM_IOCTL_GEM_CLOSE DRM_IOW (0x09, struct drm_gem_close) #define DRM_IOCTL_GEM_FLINK DRM_IOWR(0x0a, struct drm_gem_flink) #define DRM_IOCTL_GEM_OPEN DRM_IOWR(0x0b, struct drm_gem_open) #define DRM_IOCTL_GET_CAP DRM_IOWR(0x0c, struct drm_get_cap) #define DRM_IOCTL_SET_CLIENT_CAP DRM_IOW( 0x0d, struct drm_set_client_cap) #define DRM_IOCTL_SET_UNIQUE DRM_IOW( 0x10, struct drm_unique) #define DRM_IOCTL_AUTH_MAGIC DRM_IOW( 0x11, struct drm_auth) #define DRM_IOCTL_BLOCK DRM_IOWR(0x12, struct drm_block) #define DRM_IOCTL_UNBLOCK DRM_IOWR(0x13, struct drm_block) #define DRM_IOCTL_CONTROL DRM_IOW( 0x14, struct drm_control) #define DRM_IOCTL_ADD_MAP DRM_IOWR(0x15, struct drm_map) #define DRM_IOCTL_ADD_BUFS DRM_IOWR(0x16, struct drm_buf_desc) #define DRM_IOCTL_MARK_BUFS DRM_IOW( 0x17, struct drm_buf_desc) #define DRM_IOCTL_INFO_BUFS DRM_IOWR(0x18, struct drm_buf_info) #define DRM_IOCTL_MAP_BUFS DRM_IOWR(0x19, struct drm_buf_map) #define DRM_IOCTL_FREE_BUFS DRM_IOW( 0x1a, struct drm_buf_free) #define DRM_IOCTL_RM_MAP DRM_IOW( 0x1b, struct drm_map) #define DRM_IOCTL_SET_SAREA_CTX DRM_IOW( 0x1c, struct drm_ctx_priv_map) #define DRM_IOCTL_GET_SAREA_CTX DRM_IOWR(0x1d, struct drm_ctx_priv_map) #define DRM_IOCTL_SET_MASTER DRM_IO(0x1e) #define DRM_IOCTL_DROP_MASTER DRM_IO(0x1f) #define DRM_IOCTL_ADD_CTX DRM_IOWR(0x20, struct drm_ctx) #define DRM_IOCTL_RM_CTX DRM_IOWR(0x21, struct drm_ctx) #define DRM_IOCTL_MOD_CTX DRM_IOW( 0x22, struct drm_ctx) #define DRM_IOCTL_GET_CTX DRM_IOWR(0x23, struct drm_ctx) #define DRM_IOCTL_SWITCH_CTX DRM_IOW( 0x24, struct drm_ctx) #define DRM_IOCTL_NEW_CTX DRM_IOW( 0x25, struct drm_ctx) #define DRM_IOCTL_RES_CTX DRM_IOWR(0x26, struct drm_ctx_res) #define DRM_IOCTL_ADD_DRAW DRM_IOWR(0x27, struct drm_draw) #define DRM_IOCTL_RM_DRAW DRM_IOWR(0x28, struct drm_draw) #define DRM_IOCTL_DMA DRM_IOWR(0x29, struct drm_dma) #define DRM_IOCTL_LOCK DRM_IOW( 0x2a, struct drm_lock) #define DRM_IOCTL_UNLOCK DRM_IOW( 0x2b, struct drm_lock) #define DRM_IOCTL_FINISH DRM_IOW( 0x2c, struct drm_lock) #define DRM_IOCTL_PRIME_HANDLE_TO_FD DRM_IOWR(0x2d, struct drm_prime_handle) #define DRM_IOCTL_PRIME_FD_TO_HANDLE DRM_IOWR(0x2e, struct drm_prime_handle) #define DRM_IOCTL_AGP_ACQUIRE DRM_IO( 0x30) #define DRM_IOCTL_AGP_RELEASE DRM_IO( 0x31) #define DRM_IOCTL_AGP_ENABLE DRM_IOW( 0x32, struct drm_agp_mode) #define DRM_IOCTL_AGP_INFO DRM_IOR( 0x33, struct drm_agp_info) #define DRM_IOCTL_AGP_ALLOC DRM_IOWR(0x34, struct drm_agp_buffer) #define DRM_IOCTL_AGP_FREE DRM_IOW( 0x35, struct drm_agp_buffer) #define DRM_IOCTL_AGP_BIND DRM_IOW( 0x36, struct drm_agp_binding) #define DRM_IOCTL_AGP_UNBIND DRM_IOW( 0x37, struct drm_agp_binding) #define DRM_IOCTL_SG_ALLOC DRM_IOWR(0x38, struct drm_scatter_gather) #define DRM_IOCTL_SG_FREE DRM_IOW( 0x39, struct drm_scatter_gather) #define DRM_IOCTL_WAIT_VBLANK DRM_IOWR(0x3a, union drm_wait_vblank) #define DRM_IOCTL_CRTC_GET_SEQUENCE DRM_IOWR(0x3b, struct drm_crtc_get_sequence) #define DRM_IOCTL_CRTC_QUEUE_SEQUENCE DRM_IOWR(0x3c, struct drm_crtc_queue_sequence) #define DRM_IOCTL_UPDATE_DRAW DRM_IOW(0x3f, struct drm_update_draw) #define DRM_IOCTL_MODE_GETRESOURCES DRM_IOWR(0xA0, struct drm_mode_card_res) #define DRM_IOCTL_MODE_GETCRTC DRM_IOWR(0xA1, struct drm_mode_crtc) #define DRM_IOCTL_MODE_SETCRTC DRM_IOWR(0xA2, struct drm_mode_crtc) #define DRM_IOCTL_MODE_CURSOR DRM_IOWR(0xA3, struct drm_mode_cursor) #define DRM_IOCTL_MODE_GETGAMMA DRM_IOWR(0xA4, struct drm_mode_crtc_lut) #define DRM_IOCTL_MODE_SETGAMMA DRM_IOWR(0xA5, struct drm_mode_crtc_lut) #define DRM_IOCTL_MODE_GETENCODER DRM_IOWR(0xA6, struct drm_mode_get_encoder) #define DRM_IOCTL_MODE_GETCONNECTOR DRM_IOWR(0xA7, struct drm_mode_get_connector) #define DRM_IOCTL_MODE_ATTACHMODE DRM_IOWR(0xA8, struct drm_mode_mode_cmd) /* deprecated (never worked) */ #define DRM_IOCTL_MODE_DETACHMODE DRM_IOWR(0xA9, struct drm_mode_mode_cmd) /* deprecated (never worked) */ #define DRM_IOCTL_MODE_GETPROPERTY DRM_IOWR(0xAA, struct drm_mode_get_property) #define DRM_IOCTL_MODE_SETPROPERTY DRM_IOWR(0xAB, struct drm_mode_connector_set_property) #define DRM_IOCTL_MODE_GETPROPBLOB DRM_IOWR(0xAC, struct drm_mode_get_blob) #define DRM_IOCTL_MODE_GETFB DRM_IOWR(0xAD, struct drm_mode_fb_cmd) #define DRM_IOCTL_MODE_ADDFB DRM_IOWR(0xAE, struct drm_mode_fb_cmd) #define DRM_IOCTL_MODE_RMFB DRM_IOWR(0xAF, unsigned int) #define DRM_IOCTL_MODE_PAGE_FLIP DRM_IOWR(0xB0, struct drm_mode_crtc_page_flip) #define DRM_IOCTL_MODE_DIRTYFB DRM_IOWR(0xB1, struct drm_mode_fb_dirty_cmd) #define DRM_IOCTL_MODE_CREATE_DUMB DRM_IOWR(0xB2, struct drm_mode_create_dumb) #define DRM_IOCTL_MODE_MAP_DUMB DRM_IOWR(0xB3, struct drm_mode_map_dumb) #define DRM_IOCTL_MODE_DESTROY_DUMB DRM_IOWR(0xB4, struct drm_mode_destroy_dumb) #define DRM_IOCTL_MODE_GETPLANERESOURCES DRM_IOWR(0xB5, struct drm_mode_get_plane_res) #define DRM_IOCTL_MODE_GETPLANE DRM_IOWR(0xB6, struct drm_mode_get_plane) #define DRM_IOCTL_MODE_SETPLANE DRM_IOWR(0xB7, struct drm_mode_set_plane) #define DRM_IOCTL_MODE_ADDFB2 DRM_IOWR(0xB8, struct drm_mode_fb_cmd2) #define DRM_IOCTL_MODE_OBJ_GETPROPERTIES DRM_IOWR(0xB9, struct drm_mode_obj_get_properties) #define DRM_IOCTL_MODE_OBJ_SETPROPERTY DRM_IOWR(0xBA, struct drm_mode_obj_set_property) #define DRM_IOCTL_MODE_CURSOR2 DRM_IOWR(0xBB, struct drm_mode_cursor2) #define DRM_IOCTL_MODE_ATOMIC DRM_IOWR(0xBC, struct drm_mode_atomic) #define DRM_IOCTL_MODE_CREATEPROPBLOB DRM_IOWR(0xBD, struct drm_mode_create_blob) #define DRM_IOCTL_MODE_DESTROYPROPBLOB DRM_IOWR(0xBE, struct drm_mode_destroy_blob) #define DRM_IOCTL_SYNCOBJ_CREATE DRM_IOWR(0xBF, struct drm_syncobj_create) #define DRM_IOCTL_SYNCOBJ_DESTROY DRM_IOWR(0xC0, struct drm_syncobj_destroy) #define DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD DRM_IOWR(0xC1, struct drm_syncobj_handle) #define DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE DRM_IOWR(0xC2, struct drm_syncobj_handle) #define DRM_IOCTL_SYNCOBJ_WAIT DRM_IOWR(0xC3, struct drm_syncobj_wait) #define DRM_IOCTL_SYNCOBJ_RESET DRM_IOWR(0xC4, struct drm_syncobj_array) #define DRM_IOCTL_SYNCOBJ_SIGNAL DRM_IOWR(0xC5, struct drm_syncobj_array) #define DRM_IOCTL_MODE_CREATE_LEASE DRM_IOWR(0xC6, struct drm_mode_create_lease) #define DRM_IOCTL_MODE_LIST_LESSEES DRM_IOWR(0xC7, struct drm_mode_list_lessees) #define DRM_IOCTL_MODE_GET_LEASE DRM_IOWR(0xC8, struct drm_mode_get_lease) #define DRM_IOCTL_MODE_REVOKE_LEASE DRM_IOWR(0xC9, struct drm_mode_revoke_lease) #define DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT DRM_IOWR(0xCA, struct drm_syncobj_timeline_wait) #define DRM_IOCTL_SYNCOBJ_QUERY DRM_IOWR(0xCB, struct drm_syncobj_timeline_array) #define DRM_IOCTL_SYNCOBJ_TRANSFER DRM_IOWR(0xCC, struct drm_syncobj_transfer) #define DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL DRM_IOWR(0xCD, struct drm_syncobj_timeline_array) /** * Device specific ioctls should only be in their respective headers * The device specific ioctl range is from 0x40 to 0x9f. * Generic IOCTLS restart at 0xA0. * * \sa drmCommandNone(), drmCommandRead(), drmCommandWrite(), and * drmCommandReadWrite(). */ #define DRM_COMMAND_BASE 0x40 #define DRM_COMMAND_END 0xA0 /** * Header for events written back to userspace on the drm fd. The * type defines the type of event, the length specifies the total * length of the event (including the header), and user_data is * typically a 64 bit value passed with the ioctl that triggered the * event. A read on the drm fd will always only return complete * events, that is, if for example the read buffer is 100 bytes, and * there are two 64 byte events pending, only one will be returned. * * Event types 0 - 0x7fffffff are generic drm events, 0x80000000 and * up are chipset specific. */ struct drm_event { __u32 type; __u32 length; }; #define DRM_EVENT_VBLANK 0x01 #define DRM_EVENT_FLIP_COMPLETE 0x02 #define DRM_EVENT_CRTC_SEQUENCE 0x03 struct drm_event_vblank { struct drm_event base; __u64 user_data; __u32 tv_sec; __u32 tv_usec; __u32 sequence; __u32 crtc_id; /* 0 on older kernels that do not support this */ }; /* Event delivered at sequence. Time stamp marks when the first pixel * of the refresh cycle leaves the display engine for the display */ struct drm_event_crtc_sequence { struct drm_event base; __u64 user_data; __s64 time_ns; __u64 sequence; }; /* typedef area */ typedef struct drm_clip_rect drm_clip_rect_t; typedef struct drm_drawable_info drm_drawable_info_t; typedef struct drm_tex_region drm_tex_region_t; typedef struct drm_hw_lock drm_hw_lock_t; typedef struct drm_version drm_version_t; typedef struct drm_unique drm_unique_t; typedef struct drm_list drm_list_t; typedef struct drm_block drm_block_t; typedef struct drm_control drm_control_t; typedef enum drm_map_type drm_map_type_t; typedef enum drm_map_flags drm_map_flags_t; typedef struct drm_ctx_priv_map drm_ctx_priv_map_t; typedef struct drm_map drm_map_t; typedef struct drm_client drm_client_t; typedef enum drm_stat_type drm_stat_type_t; typedef struct drm_stats drm_stats_t; typedef enum drm_lock_flags drm_lock_flags_t; typedef struct drm_lock drm_lock_t; typedef enum drm_dma_flags drm_dma_flags_t; typedef struct drm_buf_desc drm_buf_desc_t; typedef struct drm_buf_info drm_buf_info_t; typedef struct drm_buf_free drm_buf_free_t; typedef struct drm_buf_pub drm_buf_pub_t; typedef struct drm_buf_map drm_buf_map_t; typedef struct drm_dma drm_dma_t; typedef union drm_wait_vblank drm_wait_vblank_t; typedef struct drm_agp_mode drm_agp_mode_t; typedef enum drm_ctx_flags drm_ctx_flags_t; typedef struct drm_ctx drm_ctx_t; typedef struct drm_ctx_res drm_ctx_res_t; typedef struct drm_draw drm_draw_t; typedef struct drm_update_draw drm_update_draw_t; typedef struct drm_auth drm_auth_t; typedef struct drm_irq_busid drm_irq_busid_t; typedef enum drm_vblank_seq_type drm_vblank_seq_type_t; typedef struct drm_agp_buffer drm_agp_buffer_t; typedef struct drm_agp_binding drm_agp_binding_t; typedef struct drm_agp_info drm_agp_info_t; typedef struct drm_scatter_gather drm_scatter_gather_t; typedef struct drm_set_version drm_set_version_t; #if defined(__cplusplus) } #endif #endif ================================================ FILE: mesa/include/drm-uapi/drm_fourcc.h ================================================ /* * Copyright 2011 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef DRM_FOURCC_H #define DRM_FOURCC_H #include "drm.h" #if defined(__cplusplus) extern "C" { #endif /** * DOC: overview * * In the DRM subsystem, framebuffer pixel formats are described using the * fourcc codes defined in `include/uapi/drm/drm_fourcc.h`. In addition to the * fourcc code, a Format Modifier may optionally be provided, in order to * further describe the buffer's format - for example tiling or compression. * * Format Modifiers * ---------------- * * Format modifiers are used in conjunction with a fourcc code, forming a * unique fourcc:modifier pair. This format:modifier pair must fully define the * format and data layout of the buffer, and should be the only way to describe * that particular buffer. * * Having multiple fourcc:modifier pairs which describe the same layout should * be avoided, as such aliases run the risk of different drivers exposing * different names for the same data format, forcing userspace to understand * that they are aliases. * * Format modifiers may change any property of the buffer, including the number * of planes and/or the required allocation size. Format modifiers are * vendor-namespaced, and as such the relationship between a fourcc code and a * modifier is specific to the modifer being used. For example, some modifiers * may preserve meaning - such as number of planes - from the fourcc code, * whereas others may not. * * Vendors should document their modifier usage in as much detail as * possible, to ensure maximum compatibility across devices, drivers and * applications. * * The authoritative list of format modifier codes is found in * `include/uapi/drm/drm_fourcc.h` */ #define fourcc_code(a, b, c, d) ((__u32)(a) | ((__u32)(b) << 8) | \ ((__u32)(c) << 16) | ((__u32)(d) << 24)) #define DRM_FORMAT_BIG_ENDIAN (1<<31) /* format is big endian instead of little endian */ /* Reserve 0 for the invalid format specifier */ #define DRM_FORMAT_INVALID 0 /* color index */ #define DRM_FORMAT_C8 fourcc_code('C', '8', ' ', ' ') /* [7:0] C */ /* 8 bpp Red */ #define DRM_FORMAT_R8 fourcc_code('R', '8', ' ', ' ') /* [7:0] R */ /* 16 bpp Red */ #define DRM_FORMAT_R16 fourcc_code('R', '1', '6', ' ') /* [15:0] R little endian */ /* 16 bpp RG */ #define DRM_FORMAT_RG88 fourcc_code('R', 'G', '8', '8') /* [15:0] R:G 8:8 little endian */ #define DRM_FORMAT_GR88 fourcc_code('G', 'R', '8', '8') /* [15:0] G:R 8:8 little endian */ /* 32 bpp RG */ #define DRM_FORMAT_RG1616 fourcc_code('R', 'G', '3', '2') /* [31:0] R:G 16:16 little endian */ #define DRM_FORMAT_GR1616 fourcc_code('G', 'R', '3', '2') /* [31:0] G:R 16:16 little endian */ /* 8 bpp RGB */ #define DRM_FORMAT_RGB332 fourcc_code('R', 'G', 'B', '8') /* [7:0] R:G:B 3:3:2 */ #define DRM_FORMAT_BGR233 fourcc_code('B', 'G', 'R', '8') /* [7:0] B:G:R 2:3:3 */ /* 16 bpp RGB */ #define DRM_FORMAT_XRGB4444 fourcc_code('X', 'R', '1', '2') /* [15:0] x:R:G:B 4:4:4:4 little endian */ #define DRM_FORMAT_XBGR4444 fourcc_code('X', 'B', '1', '2') /* [15:0] x:B:G:R 4:4:4:4 little endian */ #define DRM_FORMAT_RGBX4444 fourcc_code('R', 'X', '1', '2') /* [15:0] R:G:B:x 4:4:4:4 little endian */ #define DRM_FORMAT_BGRX4444 fourcc_code('B', 'X', '1', '2') /* [15:0] B:G:R:x 4:4:4:4 little endian */ #define DRM_FORMAT_ARGB4444 fourcc_code('A', 'R', '1', '2') /* [15:0] A:R:G:B 4:4:4:4 little endian */ #define DRM_FORMAT_ABGR4444 fourcc_code('A', 'B', '1', '2') /* [15:0] A:B:G:R 4:4:4:4 little endian */ #define DRM_FORMAT_RGBA4444 fourcc_code('R', 'A', '1', '2') /* [15:0] R:G:B:A 4:4:4:4 little endian */ #define DRM_FORMAT_BGRA4444 fourcc_code('B', 'A', '1', '2') /* [15:0] B:G:R:A 4:4:4:4 little endian */ #define DRM_FORMAT_XRGB1555 fourcc_code('X', 'R', '1', '5') /* [15:0] x:R:G:B 1:5:5:5 little endian */ #define DRM_FORMAT_XBGR1555 fourcc_code('X', 'B', '1', '5') /* [15:0] x:B:G:R 1:5:5:5 little endian */ #define DRM_FORMAT_RGBX5551 fourcc_code('R', 'X', '1', '5') /* [15:0] R:G:B:x 5:5:5:1 little endian */ #define DRM_FORMAT_BGRX5551 fourcc_code('B', 'X', '1', '5') /* [15:0] B:G:R:x 5:5:5:1 little endian */ #define DRM_FORMAT_ARGB1555 fourcc_code('A', 'R', '1', '5') /* [15:0] A:R:G:B 1:5:5:5 little endian */ #define DRM_FORMAT_ABGR1555 fourcc_code('A', 'B', '1', '5') /* [15:0] A:B:G:R 1:5:5:5 little endian */ #define DRM_FORMAT_RGBA5551 fourcc_code('R', 'A', '1', '5') /* [15:0] R:G:B:A 5:5:5:1 little endian */ #define DRM_FORMAT_BGRA5551 fourcc_code('B', 'A', '1', '5') /* [15:0] B:G:R:A 5:5:5:1 little endian */ #define DRM_FORMAT_RGB565 fourcc_code('R', 'G', '1', '6') /* [15:0] R:G:B 5:6:5 little endian */ #define DRM_FORMAT_BGR565 fourcc_code('B', 'G', '1', '6') /* [15:0] B:G:R 5:6:5 little endian */ /* 24 bpp RGB */ #define DRM_FORMAT_RGB888 fourcc_code('R', 'G', '2', '4') /* [23:0] R:G:B little endian */ #define DRM_FORMAT_BGR888 fourcc_code('B', 'G', '2', '4') /* [23:0] B:G:R little endian */ /* 32 bpp RGB */ #define DRM_FORMAT_XRGB8888 fourcc_code('X', 'R', '2', '4') /* [31:0] x:R:G:B 8:8:8:8 little endian */ #define DRM_FORMAT_XBGR8888 fourcc_code('X', 'B', '2', '4') /* [31:0] x:B:G:R 8:8:8:8 little endian */ #define DRM_FORMAT_RGBX8888 fourcc_code('R', 'X', '2', '4') /* [31:0] R:G:B:x 8:8:8:8 little endian */ #define DRM_FORMAT_BGRX8888 fourcc_code('B', 'X', '2', '4') /* [31:0] B:G:R:x 8:8:8:8 little endian */ #define DRM_FORMAT_ARGB8888 fourcc_code('A', 'R', '2', '4') /* [31:0] A:R:G:B 8:8:8:8 little endian */ #define DRM_FORMAT_ABGR8888 fourcc_code('A', 'B', '2', '4') /* [31:0] A:B:G:R 8:8:8:8 little endian */ #define DRM_FORMAT_RGBA8888 fourcc_code('R', 'A', '2', '4') /* [31:0] R:G:B:A 8:8:8:8 little endian */ #define DRM_FORMAT_BGRA8888 fourcc_code('B', 'A', '2', '4') /* [31:0] B:G:R:A 8:8:8:8 little endian */ #define DRM_FORMAT_XRGB2101010 fourcc_code('X', 'R', '3', '0') /* [31:0] x:R:G:B 2:10:10:10 little endian */ #define DRM_FORMAT_XBGR2101010 fourcc_code('X', 'B', '3', '0') /* [31:0] x:B:G:R 2:10:10:10 little endian */ #define DRM_FORMAT_RGBX1010102 fourcc_code('R', 'X', '3', '0') /* [31:0] R:G:B:x 10:10:10:2 little endian */ #define DRM_FORMAT_BGRX1010102 fourcc_code('B', 'X', '3', '0') /* [31:0] B:G:R:x 10:10:10:2 little endian */ #define DRM_FORMAT_ARGB2101010 fourcc_code('A', 'R', '3', '0') /* [31:0] A:R:G:B 2:10:10:10 little endian */ #define DRM_FORMAT_ABGR2101010 fourcc_code('A', 'B', '3', '0') /* [31:0] A:B:G:R 2:10:10:10 little endian */ #define DRM_FORMAT_RGBA1010102 fourcc_code('R', 'A', '3', '0') /* [31:0] R:G:B:A 10:10:10:2 little endian */ #define DRM_FORMAT_BGRA1010102 fourcc_code('B', 'A', '3', '0') /* [31:0] B:G:R:A 10:10:10:2 little endian */ /* * Floating point 64bpp RGB * IEEE 754-2008 binary16 half-precision float * [15:0] sign:exponent:mantissa 1:5:10 */ #define DRM_FORMAT_XRGB16161616F fourcc_code('X', 'R', '4', 'H') /* [63:0] x:R:G:B 16:16:16:16 little endian */ #define DRM_FORMAT_XBGR16161616F fourcc_code('X', 'B', '4', 'H') /* [63:0] x:B:G:R 16:16:16:16 little endian */ #define DRM_FORMAT_ARGB16161616F fourcc_code('A', 'R', '4', 'H') /* [63:0] A:R:G:B 16:16:16:16 little endian */ #define DRM_FORMAT_ABGR16161616F fourcc_code('A', 'B', '4', 'H') /* [63:0] A:B:G:R 16:16:16:16 little endian */ /* packed YCbCr */ #define DRM_FORMAT_YUYV fourcc_code('Y', 'U', 'Y', 'V') /* [31:0] Cr0:Y1:Cb0:Y0 8:8:8:8 little endian */ #define DRM_FORMAT_YVYU fourcc_code('Y', 'V', 'Y', 'U') /* [31:0] Cb0:Y1:Cr0:Y0 8:8:8:8 little endian */ #define DRM_FORMAT_UYVY fourcc_code('U', 'Y', 'V', 'Y') /* [31:0] Y1:Cr0:Y0:Cb0 8:8:8:8 little endian */ #define DRM_FORMAT_VYUY fourcc_code('V', 'Y', 'U', 'Y') /* [31:0] Y1:Cb0:Y0:Cr0 8:8:8:8 little endian */ #define DRM_FORMAT_AYUV fourcc_code('A', 'Y', 'U', 'V') /* [31:0] A:Y:Cb:Cr 8:8:8:8 little endian */ #define DRM_FORMAT_XYUV8888 fourcc_code('X', 'Y', 'U', 'V') /* [31:0] X:Y:Cb:Cr 8:8:8:8 little endian */ #define DRM_FORMAT_VUY888 fourcc_code('V', 'U', '2', '4') /* [23:0] Cr:Cb:Y 8:8:8 little endian */ #define DRM_FORMAT_VUY101010 fourcc_code('V', 'U', '3', '0') /* Y followed by U then V, 10:10:10. Non-linear modifier only */ /* * packed Y2xx indicate for each component, xx valid data occupy msb * 16-xx padding occupy lsb */ #define DRM_FORMAT_Y210 fourcc_code('Y', '2', '1', '0') /* [63:0] Cr0:0:Y1:0:Cb0:0:Y0:0 10:6:10:6:10:6:10:6 little endian per 2 Y pixels */ #define DRM_FORMAT_Y212 fourcc_code('Y', '2', '1', '2') /* [63:0] Cr0:0:Y1:0:Cb0:0:Y0:0 12:4:12:4:12:4:12:4 little endian per 2 Y pixels */ #define DRM_FORMAT_Y216 fourcc_code('Y', '2', '1', '6') /* [63:0] Cr0:Y1:Cb0:Y0 16:16:16:16 little endian per 2 Y pixels */ /* * packed Y4xx indicate for each component, xx valid data occupy msb * 16-xx padding occupy lsb except Y410 */ #define DRM_FORMAT_Y410 fourcc_code('Y', '4', '1', '0') /* [31:0] A:Cr:Y:Cb 2:10:10:10 little endian */ #define DRM_FORMAT_Y412 fourcc_code('Y', '4', '1', '2') /* [63:0] A:0:Cr:0:Y:0:Cb:0 12:4:12:4:12:4:12:4 little endian */ #define DRM_FORMAT_Y416 fourcc_code('Y', '4', '1', '6') /* [63:0] A:Cr:Y:Cb 16:16:16:16 little endian */ #define DRM_FORMAT_XVYU2101010 fourcc_code('X', 'V', '3', '0') /* [31:0] X:Cr:Y:Cb 2:10:10:10 little endian */ #define DRM_FORMAT_XVYU12_16161616 fourcc_code('X', 'V', '3', '6') /* [63:0] X:0:Cr:0:Y:0:Cb:0 12:4:12:4:12:4:12:4 little endian */ #define DRM_FORMAT_XVYU16161616 fourcc_code('X', 'V', '4', '8') /* [63:0] X:Cr:Y:Cb 16:16:16:16 little endian */ /* * packed YCbCr420 2x2 tiled formats * first 64 bits will contain Y,Cb,Cr components for a 2x2 tile */ /* [63:0] A3:A2:Y3:0:Cr0:0:Y2:0:A1:A0:Y1:0:Cb0:0:Y0:0 1:1:8:2:8:2:8:2:1:1:8:2:8:2:8:2 little endian */ #define DRM_FORMAT_Y0L0 fourcc_code('Y', '0', 'L', '0') /* [63:0] X3:X2:Y3:0:Cr0:0:Y2:0:X1:X0:Y1:0:Cb0:0:Y0:0 1:1:8:2:8:2:8:2:1:1:8:2:8:2:8:2 little endian */ #define DRM_FORMAT_X0L0 fourcc_code('X', '0', 'L', '0') /* [63:0] A3:A2:Y3:Cr0:Y2:A1:A0:Y1:Cb0:Y0 1:1:10:10:10:1:1:10:10:10 little endian */ #define DRM_FORMAT_Y0L2 fourcc_code('Y', '0', 'L', '2') /* [63:0] X3:X2:Y3:Cr0:Y2:X1:X0:Y1:Cb0:Y0 1:1:10:10:10:1:1:10:10:10 little endian */ #define DRM_FORMAT_X0L2 fourcc_code('X', '0', 'L', '2') /* * 1-plane YUV 4:2:0 * In these formats, the component ordering is specified (Y, followed by U * then V), but the exact Linear layout is undefined. * These formats can only be used with a non-Linear modifier. */ #define DRM_FORMAT_YUV420_8BIT fourcc_code('Y', 'U', '0', '8') #define DRM_FORMAT_YUV420_10BIT fourcc_code('Y', 'U', '1', '0') /* * 2 plane RGB + A * index 0 = RGB plane, same format as the corresponding non _A8 format has * index 1 = A plane, [7:0] A */ #define DRM_FORMAT_XRGB8888_A8 fourcc_code('X', 'R', 'A', '8') #define DRM_FORMAT_XBGR8888_A8 fourcc_code('X', 'B', 'A', '8') #define DRM_FORMAT_RGBX8888_A8 fourcc_code('R', 'X', 'A', '8') #define DRM_FORMAT_BGRX8888_A8 fourcc_code('B', 'X', 'A', '8') #define DRM_FORMAT_RGB888_A8 fourcc_code('R', '8', 'A', '8') #define DRM_FORMAT_BGR888_A8 fourcc_code('B', '8', 'A', '8') #define DRM_FORMAT_RGB565_A8 fourcc_code('R', '5', 'A', '8') #define DRM_FORMAT_BGR565_A8 fourcc_code('B', '5', 'A', '8') /* * 2 plane YCbCr * index 0 = Y plane, [7:0] Y * index 1 = Cr:Cb plane, [15:0] Cr:Cb little endian * or * index 1 = Cb:Cr plane, [15:0] Cb:Cr little endian */ #define DRM_FORMAT_NV12 fourcc_code('N', 'V', '1', '2') /* 2x2 subsampled Cr:Cb plane */ #define DRM_FORMAT_NV21 fourcc_code('N', 'V', '2', '1') /* 2x2 subsampled Cb:Cr plane */ #define DRM_FORMAT_NV16 fourcc_code('N', 'V', '1', '6') /* 2x1 subsampled Cr:Cb plane */ #define DRM_FORMAT_NV61 fourcc_code('N', 'V', '6', '1') /* 2x1 subsampled Cb:Cr plane */ #define DRM_FORMAT_NV24 fourcc_code('N', 'V', '2', '4') /* non-subsampled Cr:Cb plane */ #define DRM_FORMAT_NV42 fourcc_code('N', 'V', '4', '2') /* non-subsampled Cb:Cr plane */ /* * 2 plane YCbCr MSB aligned * index 0 = Y plane, [15:0] Y:x [10:6] little endian * index 1 = Cr:Cb plane, [31:0] Cr:x:Cb:x [10:6:10:6] little endian */ #define DRM_FORMAT_P210 fourcc_code('P', '2', '1', '0') /* 2x1 subsampled Cr:Cb plane, 10 bit per channel */ /* * 2 plane YCbCr MSB aligned * index 0 = Y plane, [15:0] Y:x [10:6] little endian * index 1 = Cr:Cb plane, [31:0] Cr:x:Cb:x [10:6:10:6] little endian */ #define DRM_FORMAT_P010 fourcc_code('P', '0', '1', '0') /* 2x2 subsampled Cr:Cb plane 10 bits per channel */ /* * 2 plane YCbCr MSB aligned * index 0 = Y plane, [15:0] Y:x [12:4] little endian * index 1 = Cr:Cb plane, [31:0] Cr:x:Cb:x [12:4:12:4] little endian */ #define DRM_FORMAT_P012 fourcc_code('P', '0', '1', '2') /* 2x2 subsampled Cr:Cb plane 12 bits per channel */ /* * 2 plane YCbCr MSB aligned * index 0 = Y plane, [15:0] Y little endian * index 1 = Cr:Cb plane, [31:0] Cr:Cb [16:16] little endian */ #define DRM_FORMAT_P016 fourcc_code('P', '0', '1', '6') /* 2x2 subsampled Cr:Cb plane 16 bits per channel */ /* * 3 plane YCbCr * index 0: Y plane, [7:0] Y * index 1: Cb plane, [7:0] Cb * index 2: Cr plane, [7:0] Cr * or * index 1: Cr plane, [7:0] Cr * index 2: Cb plane, [7:0] Cb */ #define DRM_FORMAT_YUV410 fourcc_code('Y', 'U', 'V', '9') /* 4x4 subsampled Cb (1) and Cr (2) planes */ #define DRM_FORMAT_YVU410 fourcc_code('Y', 'V', 'U', '9') /* 4x4 subsampled Cr (1) and Cb (2) planes */ #define DRM_FORMAT_YUV411 fourcc_code('Y', 'U', '1', '1') /* 4x1 subsampled Cb (1) and Cr (2) planes */ #define DRM_FORMAT_YVU411 fourcc_code('Y', 'V', '1', '1') /* 4x1 subsampled Cr (1) and Cb (2) planes */ #define DRM_FORMAT_YUV420 fourcc_code('Y', 'U', '1', '2') /* 2x2 subsampled Cb (1) and Cr (2) planes */ #define DRM_FORMAT_YVU420 fourcc_code('Y', 'V', '1', '2') /* 2x2 subsampled Cr (1) and Cb (2) planes */ #define DRM_FORMAT_YUV422 fourcc_code('Y', 'U', '1', '6') /* 2x1 subsampled Cb (1) and Cr (2) planes */ #define DRM_FORMAT_YVU422 fourcc_code('Y', 'V', '1', '6') /* 2x1 subsampled Cr (1) and Cb (2) planes */ #define DRM_FORMAT_YUV444 fourcc_code('Y', 'U', '2', '4') /* non-subsampled Cb (1) and Cr (2) planes */ #define DRM_FORMAT_YVU444 fourcc_code('Y', 'V', '2', '4') /* non-subsampled Cr (1) and Cb (2) planes */ /* * Format Modifiers: * * Format modifiers describe, typically, a re-ordering or modification * of the data in a plane of an FB. This can be used to express tiled/ * swizzled formats, or compression, or a combination of the two. * * The upper 8 bits of the format modifier are a vendor-id as assigned * below. The lower 56 bits are assigned as vendor sees fit. */ /* Vendor Ids: */ #define DRM_FORMAT_MOD_NONE 0 #define DRM_FORMAT_MOD_VENDOR_NONE 0 #define DRM_FORMAT_MOD_VENDOR_INTEL 0x01 #define DRM_FORMAT_MOD_VENDOR_AMD 0x02 #define DRM_FORMAT_MOD_VENDOR_NVIDIA 0x03 #define DRM_FORMAT_MOD_VENDOR_SAMSUNG 0x04 #define DRM_FORMAT_MOD_VENDOR_QCOM 0x05 #define DRM_FORMAT_MOD_VENDOR_VIVANTE 0x06 #define DRM_FORMAT_MOD_VENDOR_BROADCOM 0x07 #define DRM_FORMAT_MOD_VENDOR_ARM 0x08 #define DRM_FORMAT_MOD_VENDOR_ALLWINNER 0x09 /* add more to the end as needed */ #define DRM_FORMAT_RESERVED ((1ULL << 56) - 1) #define fourcc_mod_code(vendor, val) \ ((((__u64)DRM_FORMAT_MOD_VENDOR_## vendor) << 56) | ((val) & 0x00ffffffffffffffULL)) /* * Format Modifier tokens: * * When adding a new token please document the layout with a code comment, * similar to the fourcc codes above. drm_fourcc.h is considered the * authoritative source for all of these. */ /* * Invalid Modifier * * This modifier can be used as a sentinel to terminate the format modifiers * list, or to initialize a variable with an invalid modifier. It might also be * used to report an error back to userspace for certain APIs. */ #define DRM_FORMAT_MOD_INVALID fourcc_mod_code(NONE, DRM_FORMAT_RESERVED) /* * Linear Layout * * Just plain linear layout. Note that this is different from no specifying any * modifier (e.g. not setting DRM_MODE_FB_MODIFIERS in the DRM_ADDFB2 ioctl), * which tells the driver to also take driver-internal information into account * and so might actually result in a tiled framebuffer. */ #define DRM_FORMAT_MOD_LINEAR fourcc_mod_code(NONE, 0) /* Intel framebuffer modifiers */ /* * Intel X-tiling layout * * This is a tiled layout using 4Kb tiles (except on gen2 where the tiles 2Kb) * in row-major layout. Within the tile bytes are laid out row-major, with * a platform-dependent stride. On top of that the memory can apply * platform-depending swizzling of some higher address bits into bit6. * * This format is highly platforms specific and not useful for cross-driver * sharing. It exists since on a given platform it does uniquely identify the * layout in a simple way for i915-specific userspace. */ #define I915_FORMAT_MOD_X_TILED fourcc_mod_code(INTEL, 1) /* * Intel Y-tiling layout * * This is a tiled layout using 4Kb tiles (except on gen2 where the tiles 2Kb) * in row-major layout. Within the tile bytes are laid out in OWORD (16 bytes) * chunks column-major, with a platform-dependent height. On top of that the * memory can apply platform-depending swizzling of some higher address bits * into bit6. * * This format is highly platforms specific and not useful for cross-driver * sharing. It exists since on a given platform it does uniquely identify the * layout in a simple way for i915-specific userspace. */ #define I915_FORMAT_MOD_Y_TILED fourcc_mod_code(INTEL, 2) /* * Intel Yf-tiling layout * * This is a tiled layout using 4Kb tiles in row-major layout. * Within the tile pixels are laid out in 16 256 byte units / sub-tiles which * are arranged in four groups (two wide, two high) with column-major layout. * Each group therefore consits out of four 256 byte units, which are also laid * out as 2x2 column-major. * 256 byte units are made out of four 64 byte blocks of pixels, producing * either a square block or a 2:1 unit. * 64 byte blocks of pixels contain four pixel rows of 16 bytes, where the width * in pixel depends on the pixel depth. */ #define I915_FORMAT_MOD_Yf_TILED fourcc_mod_code(INTEL, 3) /* * Intel color control surface (CCS) for render compression * * The framebuffer format must be one of the 8:8:8:8 RGB formats. * The main surface will be plane index 0 and must be Y/Yf-tiled, * the CCS will be plane index 1. * * Each CCS tile matches a 1024x512 pixel area of the main surface. * To match certain aspects of the 3D hardware the CCS is * considered to be made up of normal 128Bx32 Y tiles, Thus * the CCS pitch must be specified in multiples of 128 bytes. * * In reality the CCS tile appears to be a 64Bx64 Y tile, composed * of QWORD (8 bytes) chunks instead of OWORD (16 bytes) chunks. * But that fact is not relevant unless the memory is accessed * directly. */ #define I915_FORMAT_MOD_Y_TILED_CCS fourcc_mod_code(INTEL, 4) #define I915_FORMAT_MOD_Yf_TILED_CCS fourcc_mod_code(INTEL, 5) /* * Tiled, NV12MT, grouped in 64 (pixels) x 32 (lines) -sized macroblocks * * Macroblocks are laid in a Z-shape, and each pixel data is following the * standard NV12 style. * As for NV12, an image is the result of two frame buffers: one for Y, * one for the interleaved Cb/Cr components (1/2 the height of the Y buffer). * Alignment requirements are (for each buffer): * - multiple of 128 pixels for the width * - multiple of 32 pixels for the height * * For more information: see https://linuxtv.org/downloads/v4l-dvb-apis/re32.html */ #define DRM_FORMAT_MOD_SAMSUNG_64_32_TILE fourcc_mod_code(SAMSUNG, 1) /* * Tiled, 16 (pixels) x 16 (lines) - sized macroblocks * * This is a simple tiled layout using tiles of 16x16 pixels in a row-major * layout. For YCbCr formats Cb/Cr components are taken in such a way that * they correspond to their 16x16 luma block. */ #define DRM_FORMAT_MOD_SAMSUNG_16_16_TILE fourcc_mod_code(SAMSUNG, 2) /* * Qualcomm Compressed Format * * Refers to a compressed variant of the base format that is compressed. * Implementation may be platform and base-format specific. * * Each macrotile consists of m x n (mostly 4 x 4) tiles. * Pixel data pitch/stride is aligned with macrotile width. * Pixel data height is aligned with macrotile height. * Entire pixel data buffer is aligned with 4k(bytes). */ #define DRM_FORMAT_MOD_QCOM_COMPRESSED fourcc_mod_code(QCOM, 1) /* Vivante framebuffer modifiers */ /* * Vivante 4x4 tiling layout * * This is a simple tiled layout using tiles of 4x4 pixels in a row-major * layout. */ #define DRM_FORMAT_MOD_VIVANTE_TILED fourcc_mod_code(VIVANTE, 1) /* * Vivante 64x64 super-tiling layout * * This is a tiled layout using 64x64 pixel super-tiles, where each super-tile * contains 8x4 groups of 2x4 tiles of 4x4 pixels (like above) each, all in row- * major layout. * * For more information: see * https://github.com/etnaviv/etna_viv/blob/master/doc/hardware.md#texture-tiling */ #define DRM_FORMAT_MOD_VIVANTE_SUPER_TILED fourcc_mod_code(VIVANTE, 2) /* * Vivante 4x4 tiling layout for dual-pipe * * Same as the 4x4 tiling layout, except every second 4x4 pixel tile starts at a * different base address. Offsets from the base addresses are therefore halved * compared to the non-split tiled layout. */ #define DRM_FORMAT_MOD_VIVANTE_SPLIT_TILED fourcc_mod_code(VIVANTE, 3) /* * Vivante 64x64 super-tiling layout for dual-pipe * * Same as the 64x64 super-tiling layout, except every second 4x4 pixel tile * starts at a different base address. Offsets from the base addresses are * therefore halved compared to the non-split super-tiled layout. */ #define DRM_FORMAT_MOD_VIVANTE_SPLIT_SUPER_TILED fourcc_mod_code(VIVANTE, 4) /* NVIDIA frame buffer modifiers */ /* * Tegra Tiled Layout, used by Tegra 2, 3 and 4. * * Pixels are arranged in simple tiles of 16 x 16 bytes. */ #define DRM_FORMAT_MOD_NVIDIA_TEGRA_TILED fourcc_mod_code(NVIDIA, 1) /* * 16Bx2 Block Linear layout, used by desktop GPUs, and Tegra K1 and later * * Pixels are arranged in 64x8 Groups Of Bytes (GOBs). GOBs are then stacked * vertically by a power of 2 (1 to 32 GOBs) to form a block. * * Within a GOB, data is ordered as 16B x 2 lines sectors laid in Z-shape. * * Parameter 'v' is the log2 encoding of the number of GOBs stacked vertically. * Valid values are: * * 0 == ONE_GOB * 1 == TWO_GOBS * 2 == FOUR_GOBS * 3 == EIGHT_GOBS * 4 == SIXTEEN_GOBS * 5 == THIRTYTWO_GOBS * * Chapter 20 "Pixel Memory Formats" of the Tegra X1 TRM describes this format * in full detail. */ #define DRM_FORMAT_MOD_NVIDIA_16BX2_BLOCK(v) \ fourcc_mod_code(NVIDIA, 0x10 | ((v) & 0xf)) #define DRM_FORMAT_MOD_NVIDIA_16BX2_BLOCK_ONE_GOB \ fourcc_mod_code(NVIDIA, 0x10) #define DRM_FORMAT_MOD_NVIDIA_16BX2_BLOCK_TWO_GOB \ fourcc_mod_code(NVIDIA, 0x11) #define DRM_FORMAT_MOD_NVIDIA_16BX2_BLOCK_FOUR_GOB \ fourcc_mod_code(NVIDIA, 0x12) #define DRM_FORMAT_MOD_NVIDIA_16BX2_BLOCK_EIGHT_GOB \ fourcc_mod_code(NVIDIA, 0x13) #define DRM_FORMAT_MOD_NVIDIA_16BX2_BLOCK_SIXTEEN_GOB \ fourcc_mod_code(NVIDIA, 0x14) #define DRM_FORMAT_MOD_NVIDIA_16BX2_BLOCK_THIRTYTWO_GOB \ fourcc_mod_code(NVIDIA, 0x15) /* * Some Broadcom modifiers take parameters, for example the number of * vertical lines in the image. Reserve the lower 32 bits for modifier * type, and the next 24 bits for parameters. Top 8 bits are the * vendor code. */ #define __fourcc_mod_broadcom_param_shift 8 #define __fourcc_mod_broadcom_param_bits 48 #define fourcc_mod_broadcom_code(val, params) \ fourcc_mod_code(BROADCOM, ((((__u64)params) << __fourcc_mod_broadcom_param_shift) | val)) #define fourcc_mod_broadcom_param(m) \ ((int)(((m) >> __fourcc_mod_broadcom_param_shift) & \ ((1ULL << __fourcc_mod_broadcom_param_bits) - 1))) #define fourcc_mod_broadcom_mod(m) \ ((m) & ~(((1ULL << __fourcc_mod_broadcom_param_bits) - 1) << \ __fourcc_mod_broadcom_param_shift)) /* * Broadcom VC4 "T" format * * This is the primary layout that the V3D GPU can texture from (it * can't do linear). The T format has: * * - 64b utiles of pixels in a raster-order grid according to cpp. It's 4x4 * pixels at 32 bit depth. * * - 1k subtiles made of a 4x4 raster-order grid of 64b utiles (so usually * 16x16 pixels). * * - 4k tiles made of a 2x2 grid of 1k subtiles (so usually 32x32 pixels). On * even 4k tile rows, they're arranged as (BL, TL, TR, BR), and on odd rows * they're (TR, BR, BL, TL), where bottom left is start of memory. * * - an image made of 4k tiles in rows either left-to-right (even rows of 4k * tiles) or right-to-left (odd rows of 4k tiles). */ #define DRM_FORMAT_MOD_BROADCOM_VC4_T_TILED fourcc_mod_code(BROADCOM, 1) /* * Broadcom SAND format * * This is the native format that the H.264 codec block uses. For VC4 * HVS, it is only valid for H.264 (NV12/21) and RGBA modes. * * The image can be considered to be split into columns, and the * columns are placed consecutively into memory. The width of those * columns can be either 32, 64, 128, or 256 pixels, but in practice * only 128 pixel columns are used. * * The pitch between the start of each column is set to optimally * switch between SDRAM banks. This is passed as the number of lines * of column width in the modifier (we can't use the stride value due * to various core checks that look at it , so you should set the * stride to width*cpp). * * Note that the column height for this format modifier is the same * for all of the planes, assuming that each column contains both Y * and UV. Some SAND-using hardware stores UV in a separate tiled * image from Y to reduce the column height, which is not supported * with these modifiers. */ #define DRM_FORMAT_MOD_BROADCOM_SAND32_COL_HEIGHT(v) \ fourcc_mod_broadcom_code(2, v) #define DRM_FORMAT_MOD_BROADCOM_SAND64_COL_HEIGHT(v) \ fourcc_mod_broadcom_code(3, v) #define DRM_FORMAT_MOD_BROADCOM_SAND128_COL_HEIGHT(v) \ fourcc_mod_broadcom_code(4, v) #define DRM_FORMAT_MOD_BROADCOM_SAND256_COL_HEIGHT(v) \ fourcc_mod_broadcom_code(5, v) #define DRM_FORMAT_MOD_BROADCOM_SAND32 \ DRM_FORMAT_MOD_BROADCOM_SAND32_COL_HEIGHT(0) #define DRM_FORMAT_MOD_BROADCOM_SAND64 \ DRM_FORMAT_MOD_BROADCOM_SAND64_COL_HEIGHT(0) #define DRM_FORMAT_MOD_BROADCOM_SAND128 \ DRM_FORMAT_MOD_BROADCOM_SAND128_COL_HEIGHT(0) #define DRM_FORMAT_MOD_BROADCOM_SAND256 \ DRM_FORMAT_MOD_BROADCOM_SAND256_COL_HEIGHT(0) /* Broadcom UIF format * * This is the common format for the current Broadcom multimedia * blocks, including V3D 3.x and newer, newer video codecs, and * displays. * * The image consists of utiles (64b blocks), UIF blocks (2x2 utiles), * and macroblocks (4x4 UIF blocks). Those 4x4 UIF block groups are * stored in columns, with padding between the columns to ensure that * moving from one column to the next doesn't hit the same SDRAM page * bank. * * To calculate the padding, it is assumed that each hardware block * and the software driving it knows the platform's SDRAM page size, * number of banks, and XOR address, and that it's identical between * all blocks using the format. This tiling modifier will use XOR as * necessary to reduce the padding. If a hardware block can't do XOR, * the assumption is that a no-XOR tiling modifier will be created. */ #define DRM_FORMAT_MOD_BROADCOM_UIF fourcc_mod_code(BROADCOM, 6) /* * Arm Framebuffer Compression (AFBC) modifiers * * AFBC is a proprietary lossless image compression protocol and format. * It provides fine-grained random access and minimizes the amount of data * transferred between IP blocks. * * AFBC has several features which may be supported and/or used, which are * represented using bits in the modifier. Not all combinations are valid, * and different devices or use-cases may support different combinations. * * Further information on the use of AFBC modifiers can be found in * Documentation/gpu/afbc.rst */ /* * The top 4 bits (out of the 56 bits alloted for specifying vendor specific * modifiers) denote the category for modifiers. Currently we have only two * categories of modifiers ie AFBC and MISC. We can have a maximum of sixteen * different categories. */ #define DRM_FORMAT_MOD_ARM_CODE(__type, __val) \ fourcc_mod_code(ARM, ((__u64)(__type) << 52) | ((__val) & 0x000fffffffffffffULL)) #define DRM_FORMAT_MOD_ARM_TYPE_AFBC 0x00 #define DRM_FORMAT_MOD_ARM_TYPE_MISC 0x01 #define DRM_FORMAT_MOD_ARM_AFBC(__afbc_mode) \ DRM_FORMAT_MOD_ARM_CODE(DRM_FORMAT_MOD_ARM_TYPE_AFBC, __afbc_mode) /* * AFBC superblock size * * Indicates the superblock size(s) used for the AFBC buffer. The buffer * size (in pixels) must be aligned to a multiple of the superblock size. * Four lowest significant bits(LSBs) are reserved for block size. * * Where one superblock size is specified, it applies to all planes of the * buffer (e.g. 16x16, 32x8). When multiple superblock sizes are specified, * the first applies to the Luma plane and the second applies to the Chroma * plane(s). e.g. (32x8_64x4 means 32x8 Luma, with 64x4 Chroma). * Multiple superblock sizes are only valid for multi-plane YCbCr formats. */ #define AFBC_FORMAT_MOD_BLOCK_SIZE_MASK 0xf #define AFBC_FORMAT_MOD_BLOCK_SIZE_16x16 (1ULL) #define AFBC_FORMAT_MOD_BLOCK_SIZE_32x8 (2ULL) #define AFBC_FORMAT_MOD_BLOCK_SIZE_64x4 (3ULL) #define AFBC_FORMAT_MOD_BLOCK_SIZE_32x8_64x4 (4ULL) /* * AFBC lossless colorspace transform * * Indicates that the buffer makes use of the AFBC lossless colorspace * transform. */ #define AFBC_FORMAT_MOD_YTR (1ULL << 4) /* * AFBC block-split * * Indicates that the payload of each superblock is split. The second * half of the payload is positioned at a predefined offset from the start * of the superblock payload. */ #define AFBC_FORMAT_MOD_SPLIT (1ULL << 5) /* * AFBC sparse layout * * This flag indicates that the payload of each superblock must be stored at a * predefined position relative to the other superblocks in the same AFBC * buffer. This order is the same order used by the header buffer. In this mode * each superblock is given the same amount of space as an uncompressed * superblock of the particular format would require, rounding up to the next * multiple of 128 bytes in size. */ #define AFBC_FORMAT_MOD_SPARSE (1ULL << 6) /* * AFBC copy-block restrict * * Buffers with this flag must obey the copy-block restriction. The restriction * is such that there are no copy-blocks referring across the border of 8x8 * blocks. For the subsampled data the 8x8 limitation is also subsampled. */ #define AFBC_FORMAT_MOD_CBR (1ULL << 7) /* * AFBC tiled layout * * The tiled layout groups superblocks in 8x8 or 4x4 tiles, where all * superblocks inside a tile are stored together in memory. 8x8 tiles are used * for pixel formats up to and including 32 bpp while 4x4 tiles are used for * larger bpp formats. The order between the tiles is scan line. * When the tiled layout is used, the buffer size (in pixels) must be aligned * to the tile size. */ #define AFBC_FORMAT_MOD_TILED (1ULL << 8) /* * AFBC solid color blocks * * Indicates that the buffer makes use of solid-color blocks, whereby bandwidth * can be reduced if a whole superblock is a single color. */ #define AFBC_FORMAT_MOD_SC (1ULL << 9) /* * AFBC double-buffer * * Indicates that the buffer is allocated in a layout safe for front-buffer * rendering. */ #define AFBC_FORMAT_MOD_DB (1ULL << 10) /* * AFBC buffer content hints * * Indicates that the buffer includes per-superblock content hints. */ #define AFBC_FORMAT_MOD_BCH (1ULL << 11) /* * Arm 16x16 Block U-Interleaved modifier * * This is used by Arm Mali Utgard and Midgard GPUs. It divides the image * into 16x16 pixel blocks. Blocks are stored linearly in order, but pixels * in the block are reordered. */ #define DRM_FORMAT_MOD_ARM_16X16_BLOCK_U_INTERLEAVED \ DRM_FORMAT_MOD_ARM_CODE(DRM_FORMAT_MOD_ARM_TYPE_MISC, 1ULL) /* * Allwinner tiled modifier * * This tiling mode is implemented by the VPU found on all Allwinner platforms, * codenamed sunxi. It is associated with a YUV format that uses either 2 or 3 * planes. * * With this tiling, the luminance samples are disposed in tiles representing * 32x32 pixels and the chrominance samples in tiles representing 32x64 pixels. * The pixel order in each tile is linear and the tiles are disposed linearly, * both in row-major order. */ #define DRM_FORMAT_MOD_ALLWINNER_TILED fourcc_mod_code(ALLWINNER, 1) #if defined(__cplusplus) } #endif #endif /* DRM_FOURCC_H */ ================================================ FILE: mesa/include/drm-uapi/drm_mode.h ================================================ /* * Copyright (c) 2007 Dave Airlie * Copyright (c) 2007 Jakob Bornecrantz * Copyright (c) 2008 Red Hat Inc. * Copyright (c) 2007-2008 Tungsten Graphics, Inc., Cedar Park, TX., USA * Copyright (c) 2007-2008 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef _DRM_MODE_H #define _DRM_MODE_H #include "drm.h" #if defined(__cplusplus) extern "C" { #endif /** * DOC: overview * * DRM exposes many UAPI and structure definition to have a consistent * and standardized interface with user. * Userspace can refer to these structure definitions and UAPI formats * to communicate to driver */ #define DRM_CONNECTOR_NAME_LEN 32 #define DRM_DISPLAY_MODE_LEN 32 #define DRM_PROP_NAME_LEN 32 #define DRM_MODE_TYPE_BUILTIN (1<<0) /* deprecated */ #define DRM_MODE_TYPE_CLOCK_C ((1<<1) | DRM_MODE_TYPE_BUILTIN) /* deprecated */ #define DRM_MODE_TYPE_CRTC_C ((1<<2) | DRM_MODE_TYPE_BUILTIN) /* deprecated */ #define DRM_MODE_TYPE_PREFERRED (1<<3) #define DRM_MODE_TYPE_DEFAULT (1<<4) /* deprecated */ #define DRM_MODE_TYPE_USERDEF (1<<5) #define DRM_MODE_TYPE_DRIVER (1<<6) #define DRM_MODE_TYPE_ALL (DRM_MODE_TYPE_PREFERRED | \ DRM_MODE_TYPE_USERDEF | \ DRM_MODE_TYPE_DRIVER) /* Video mode flags */ /* bit compatible with the xrandr RR_ definitions (bits 0-13) * * ABI warning: Existing userspace really expects * the mode flags to match the xrandr definitions. Any * changes that don't match the xrandr definitions will * likely need a new client cap or some other mechanism * to avoid breaking existing userspace. This includes * allocating new flags in the previously unused bits! */ #define DRM_MODE_FLAG_PHSYNC (1<<0) #define DRM_MODE_FLAG_NHSYNC (1<<1) #define DRM_MODE_FLAG_PVSYNC (1<<2) #define DRM_MODE_FLAG_NVSYNC (1<<3) #define DRM_MODE_FLAG_INTERLACE (1<<4) #define DRM_MODE_FLAG_DBLSCAN (1<<5) #define DRM_MODE_FLAG_CSYNC (1<<6) #define DRM_MODE_FLAG_PCSYNC (1<<7) #define DRM_MODE_FLAG_NCSYNC (1<<8) #define DRM_MODE_FLAG_HSKEW (1<<9) /* hskew provided */ #define DRM_MODE_FLAG_BCAST (1<<10) /* deprecated */ #define DRM_MODE_FLAG_PIXMUX (1<<11) /* deprecated */ #define DRM_MODE_FLAG_DBLCLK (1<<12) #define DRM_MODE_FLAG_CLKDIV2 (1<<13) /* * When adding a new stereo mode don't forget to adjust DRM_MODE_FLAGS_3D_MAX * (define not exposed to user space). */ #define DRM_MODE_FLAG_3D_MASK (0x1f<<14) #define DRM_MODE_FLAG_3D_NONE (0<<14) #define DRM_MODE_FLAG_3D_FRAME_PACKING (1<<14) #define DRM_MODE_FLAG_3D_FIELD_ALTERNATIVE (2<<14) #define DRM_MODE_FLAG_3D_LINE_ALTERNATIVE (3<<14) #define DRM_MODE_FLAG_3D_SIDE_BY_SIDE_FULL (4<<14) #define DRM_MODE_FLAG_3D_L_DEPTH (5<<14) #define DRM_MODE_FLAG_3D_L_DEPTH_GFX_GFX_DEPTH (6<<14) #define DRM_MODE_FLAG_3D_TOP_AND_BOTTOM (7<<14) #define DRM_MODE_FLAG_3D_SIDE_BY_SIDE_HALF (8<<14) /* Picture aspect ratio options */ #define DRM_MODE_PICTURE_ASPECT_NONE 0 #define DRM_MODE_PICTURE_ASPECT_4_3 1 #define DRM_MODE_PICTURE_ASPECT_16_9 2 #define DRM_MODE_PICTURE_ASPECT_64_27 3 #define DRM_MODE_PICTURE_ASPECT_256_135 4 /* Content type options */ #define DRM_MODE_CONTENT_TYPE_NO_DATA 0 #define DRM_MODE_CONTENT_TYPE_GRAPHICS 1 #define DRM_MODE_CONTENT_TYPE_PHOTO 2 #define DRM_MODE_CONTENT_TYPE_CINEMA 3 #define DRM_MODE_CONTENT_TYPE_GAME 4 /* Aspect ratio flag bitmask (4 bits 22:19) */ #define DRM_MODE_FLAG_PIC_AR_MASK (0x0F<<19) #define DRM_MODE_FLAG_PIC_AR_NONE \ (DRM_MODE_PICTURE_ASPECT_NONE<<19) #define DRM_MODE_FLAG_PIC_AR_4_3 \ (DRM_MODE_PICTURE_ASPECT_4_3<<19) #define DRM_MODE_FLAG_PIC_AR_16_9 \ (DRM_MODE_PICTURE_ASPECT_16_9<<19) #define DRM_MODE_FLAG_PIC_AR_64_27 \ (DRM_MODE_PICTURE_ASPECT_64_27<<19) #define DRM_MODE_FLAG_PIC_AR_256_135 \ (DRM_MODE_PICTURE_ASPECT_256_135<<19) #define DRM_MODE_FLAG_ALL (DRM_MODE_FLAG_PHSYNC | \ DRM_MODE_FLAG_NHSYNC | \ DRM_MODE_FLAG_PVSYNC | \ DRM_MODE_FLAG_NVSYNC | \ DRM_MODE_FLAG_INTERLACE | \ DRM_MODE_FLAG_DBLSCAN | \ DRM_MODE_FLAG_CSYNC | \ DRM_MODE_FLAG_PCSYNC | \ DRM_MODE_FLAG_NCSYNC | \ DRM_MODE_FLAG_HSKEW | \ DRM_MODE_FLAG_DBLCLK | \ DRM_MODE_FLAG_CLKDIV2 | \ DRM_MODE_FLAG_3D_MASK) /* DPMS flags */ /* bit compatible with the xorg definitions. */ #define DRM_MODE_DPMS_ON 0 #define DRM_MODE_DPMS_STANDBY 1 #define DRM_MODE_DPMS_SUSPEND 2 #define DRM_MODE_DPMS_OFF 3 /* Scaling mode options */ #define DRM_MODE_SCALE_NONE 0 /* Unmodified timing (display or software can still scale) */ #define DRM_MODE_SCALE_FULLSCREEN 1 /* Full screen, ignore aspect */ #define DRM_MODE_SCALE_CENTER 2 /* Centered, no scaling */ #define DRM_MODE_SCALE_ASPECT 3 /* Full screen, preserve aspect */ /* Dithering mode options */ #define DRM_MODE_DITHERING_OFF 0 #define DRM_MODE_DITHERING_ON 1 #define DRM_MODE_DITHERING_AUTO 2 /* Dirty info options */ #define DRM_MODE_DIRTY_OFF 0 #define DRM_MODE_DIRTY_ON 1 #define DRM_MODE_DIRTY_ANNOTATE 2 /* Link Status options */ #define DRM_MODE_LINK_STATUS_GOOD 0 #define DRM_MODE_LINK_STATUS_BAD 1 /* * DRM_MODE_ROTATE_ * * Signals that a drm plane is been rotated degrees in counter * clockwise direction. * * This define is provided as a convenience, looking up the property id * using the name->prop id lookup is the preferred method. */ #define DRM_MODE_ROTATE_0 (1<<0) #define DRM_MODE_ROTATE_90 (1<<1) #define DRM_MODE_ROTATE_180 (1<<2) #define DRM_MODE_ROTATE_270 (1<<3) /* * DRM_MODE_ROTATE_MASK * * Bitmask used to look for drm plane rotations. */ #define DRM_MODE_ROTATE_MASK (\ DRM_MODE_ROTATE_0 | \ DRM_MODE_ROTATE_90 | \ DRM_MODE_ROTATE_180 | \ DRM_MODE_ROTATE_270) /* * DRM_MODE_REFLECT_ * * Signals that the contents of a drm plane is reflected along the axis, * in the same way as mirroring. * See kerneldoc chapter "Plane Composition Properties" for more details. * * This define is provided as a convenience, looking up the property id * using the name->prop id lookup is the preferred method. */ #define DRM_MODE_REFLECT_X (1<<4) #define DRM_MODE_REFLECT_Y (1<<5) /* * DRM_MODE_REFLECT_MASK * * Bitmask used to look for drm plane reflections. */ #define DRM_MODE_REFLECT_MASK (\ DRM_MODE_REFLECT_X | \ DRM_MODE_REFLECT_Y) /* Content Protection Flags */ #define DRM_MODE_CONTENT_PROTECTION_UNDESIRED 0 #define DRM_MODE_CONTENT_PROTECTION_DESIRED 1 #define DRM_MODE_CONTENT_PROTECTION_ENABLED 2 struct drm_mode_modeinfo { __u32 clock; __u16 hdisplay; __u16 hsync_start; __u16 hsync_end; __u16 htotal; __u16 hskew; __u16 vdisplay; __u16 vsync_start; __u16 vsync_end; __u16 vtotal; __u16 vscan; __u32 vrefresh; __u32 flags; __u32 type; char name[DRM_DISPLAY_MODE_LEN]; }; struct drm_mode_card_res { __u64 fb_id_ptr; __u64 crtc_id_ptr; __u64 connector_id_ptr; __u64 encoder_id_ptr; __u32 count_fbs; __u32 count_crtcs; __u32 count_connectors; __u32 count_encoders; __u32 min_width; __u32 max_width; __u32 min_height; __u32 max_height; }; struct drm_mode_crtc { __u64 set_connectors_ptr; __u32 count_connectors; __u32 crtc_id; /**< Id */ __u32 fb_id; /**< Id of framebuffer */ __u32 x; /**< x Position on the framebuffer */ __u32 y; /**< y Position on the framebuffer */ __u32 gamma_size; __u32 mode_valid; struct drm_mode_modeinfo mode; }; #define DRM_MODE_PRESENT_TOP_FIELD (1<<0) #define DRM_MODE_PRESENT_BOTTOM_FIELD (1<<1) /* Planes blend with or override other bits on the CRTC */ struct drm_mode_set_plane { __u32 plane_id; __u32 crtc_id; __u32 fb_id; /* fb object contains surface format type */ __u32 flags; /* see above flags */ /* Signed dest location allows it to be partially off screen */ __s32 crtc_x; __s32 crtc_y; __u32 crtc_w; __u32 crtc_h; /* Source values are 16.16 fixed point */ __u32 src_x; __u32 src_y; __u32 src_h; __u32 src_w; }; struct drm_mode_get_plane { __u32 plane_id; __u32 crtc_id; __u32 fb_id; __u32 possible_crtcs; __u32 gamma_size; __u32 count_format_types; __u64 format_type_ptr; }; struct drm_mode_get_plane_res { __u64 plane_id_ptr; __u32 count_planes; }; #define DRM_MODE_ENCODER_NONE 0 #define DRM_MODE_ENCODER_DAC 1 #define DRM_MODE_ENCODER_TMDS 2 #define DRM_MODE_ENCODER_LVDS 3 #define DRM_MODE_ENCODER_TVDAC 4 #define DRM_MODE_ENCODER_VIRTUAL 5 #define DRM_MODE_ENCODER_DSI 6 #define DRM_MODE_ENCODER_DPMST 7 #define DRM_MODE_ENCODER_DPI 8 struct drm_mode_get_encoder { __u32 encoder_id; __u32 encoder_type; __u32 crtc_id; /**< Id of crtc */ __u32 possible_crtcs; __u32 possible_clones; }; /* This is for connectors with multiple signal types. */ /* Try to match DRM_MODE_CONNECTOR_X as closely as possible. */ enum drm_mode_subconnector { DRM_MODE_SUBCONNECTOR_Automatic = 0, DRM_MODE_SUBCONNECTOR_Unknown = 0, DRM_MODE_SUBCONNECTOR_DVID = 3, DRM_MODE_SUBCONNECTOR_DVIA = 4, DRM_MODE_SUBCONNECTOR_Composite = 5, DRM_MODE_SUBCONNECTOR_SVIDEO = 6, DRM_MODE_SUBCONNECTOR_Component = 8, DRM_MODE_SUBCONNECTOR_SCART = 9, }; #define DRM_MODE_CONNECTOR_Unknown 0 #define DRM_MODE_CONNECTOR_VGA 1 #define DRM_MODE_CONNECTOR_DVII 2 #define DRM_MODE_CONNECTOR_DVID 3 #define DRM_MODE_CONNECTOR_DVIA 4 #define DRM_MODE_CONNECTOR_Composite 5 #define DRM_MODE_CONNECTOR_SVIDEO 6 #define DRM_MODE_CONNECTOR_LVDS 7 #define DRM_MODE_CONNECTOR_Component 8 #define DRM_MODE_CONNECTOR_9PinDIN 9 #define DRM_MODE_CONNECTOR_DisplayPort 10 #define DRM_MODE_CONNECTOR_HDMIA 11 #define DRM_MODE_CONNECTOR_HDMIB 12 #define DRM_MODE_CONNECTOR_TV 13 #define DRM_MODE_CONNECTOR_eDP 14 #define DRM_MODE_CONNECTOR_VIRTUAL 15 #define DRM_MODE_CONNECTOR_DSI 16 #define DRM_MODE_CONNECTOR_DPI 17 #define DRM_MODE_CONNECTOR_WRITEBACK 18 #define DRM_MODE_CONNECTOR_SPI 19 struct drm_mode_get_connector { __u64 encoders_ptr; __u64 modes_ptr; __u64 props_ptr; __u64 prop_values_ptr; __u32 count_modes; __u32 count_props; __u32 count_encoders; __u32 encoder_id; /**< Current Encoder */ __u32 connector_id; /**< Id */ __u32 connector_type; __u32 connector_type_id; __u32 connection; __u32 mm_width; /**< width in millimeters */ __u32 mm_height; /**< height in millimeters */ __u32 subpixel; __u32 pad; }; #define DRM_MODE_PROP_PENDING (1<<0) /* deprecated, do not use */ #define DRM_MODE_PROP_RANGE (1<<1) #define DRM_MODE_PROP_IMMUTABLE (1<<2) #define DRM_MODE_PROP_ENUM (1<<3) /* enumerated type with text strings */ #define DRM_MODE_PROP_BLOB (1<<4) #define DRM_MODE_PROP_BITMASK (1<<5) /* bitmask of enumerated types */ /* non-extended types: legacy bitmask, one bit per type: */ #define DRM_MODE_PROP_LEGACY_TYPE ( \ DRM_MODE_PROP_RANGE | \ DRM_MODE_PROP_ENUM | \ DRM_MODE_PROP_BLOB | \ DRM_MODE_PROP_BITMASK) /* extended-types: rather than continue to consume a bit per type, * grab a chunk of the bits to use as integer type id. */ #define DRM_MODE_PROP_EXTENDED_TYPE 0x0000ffc0 #define DRM_MODE_PROP_TYPE(n) ((n) << 6) #define DRM_MODE_PROP_OBJECT DRM_MODE_PROP_TYPE(1) #define DRM_MODE_PROP_SIGNED_RANGE DRM_MODE_PROP_TYPE(2) /* the PROP_ATOMIC flag is used to hide properties from userspace that * is not aware of atomic properties. This is mostly to work around * older userspace (DDX drivers) that read/write each prop they find, * witout being aware that this could be triggering a lengthy modeset. */ #define DRM_MODE_PROP_ATOMIC 0x80000000 struct drm_mode_property_enum { __u64 value; char name[DRM_PROP_NAME_LEN]; }; struct drm_mode_get_property { __u64 values_ptr; /* values and blob lengths */ __u64 enum_blob_ptr; /* enum and blob id ptrs */ __u32 prop_id; __u32 flags; char name[DRM_PROP_NAME_LEN]; __u32 count_values; /* This is only used to count enum values, not blobs. The _blobs is * simply because of a historical reason, i.e. backwards compat. */ __u32 count_enum_blobs; }; struct drm_mode_connector_set_property { __u64 value; __u32 prop_id; __u32 connector_id; }; #define DRM_MODE_OBJECT_CRTC 0xcccccccc #define DRM_MODE_OBJECT_CONNECTOR 0xc0c0c0c0 #define DRM_MODE_OBJECT_ENCODER 0xe0e0e0e0 #define DRM_MODE_OBJECT_MODE 0xdededede #define DRM_MODE_OBJECT_PROPERTY 0xb0b0b0b0 #define DRM_MODE_OBJECT_FB 0xfbfbfbfb #define DRM_MODE_OBJECT_BLOB 0xbbbbbbbb #define DRM_MODE_OBJECT_PLANE 0xeeeeeeee #define DRM_MODE_OBJECT_ANY 0 struct drm_mode_obj_get_properties { __u64 props_ptr; __u64 prop_values_ptr; __u32 count_props; __u32 obj_id; __u32 obj_type; }; struct drm_mode_obj_set_property { __u64 value; __u32 prop_id; __u32 obj_id; __u32 obj_type; }; struct drm_mode_get_blob { __u32 blob_id; __u32 length; __u64 data; }; struct drm_mode_fb_cmd { __u32 fb_id; __u32 width; __u32 height; __u32 pitch; __u32 bpp; __u32 depth; /* driver specific handle */ __u32 handle; }; #define DRM_MODE_FB_INTERLACED (1<<0) /* for interlaced framebuffers */ #define DRM_MODE_FB_MODIFIERS (1<<1) /* enables ->modifer[] */ struct drm_mode_fb_cmd2 { __u32 fb_id; __u32 width; __u32 height; __u32 pixel_format; /* fourcc code from drm_fourcc.h */ __u32 flags; /* see above flags */ /* * In case of planar formats, this ioctl allows up to 4 * buffer objects with offsets and pitches per plane. * The pitch and offset order is dictated by the fourcc, * e.g. NV12 (http://fourcc.org/yuv.php#NV12) is described as: * * YUV 4:2:0 image with a plane of 8 bit Y samples * followed by an interleaved U/V plane containing * 8 bit 2x2 subsampled colour difference samples. * * So it would consist of Y as offsets[0] and UV as * offsets[1]. Note that offsets[0] will generally * be 0 (but this is not required). * * To accommodate tiled, compressed, etc formats, a * modifier can be specified. The default value of zero * indicates "native" format as specified by the fourcc. * Vendor specific modifier token. Note that even though * it looks like we have a modifier per-plane, we in fact * do not. The modifier for each plane must be identical. * Thus all combinations of different data layouts for * multi plane formats must be enumerated as separate * modifiers. */ __u32 handles[4]; __u32 pitches[4]; /* pitch for each plane */ __u32 offsets[4]; /* offset of each plane */ __u64 modifier[4]; /* ie, tiling, compress */ }; #define DRM_MODE_FB_DIRTY_ANNOTATE_COPY 0x01 #define DRM_MODE_FB_DIRTY_ANNOTATE_FILL 0x02 #define DRM_MODE_FB_DIRTY_FLAGS 0x03 #define DRM_MODE_FB_DIRTY_MAX_CLIPS 256 /* * Mark a region of a framebuffer as dirty. * * Some hardware does not automatically update display contents * as a hardware or software draw to a framebuffer. This ioctl * allows userspace to tell the kernel and the hardware what * regions of the framebuffer have changed. * * The kernel or hardware is free to update more then just the * region specified by the clip rects. The kernel or hardware * may also delay and/or coalesce several calls to dirty into a * single update. * * Userspace may annotate the updates, the annotates are a * promise made by the caller that the change is either a copy * of pixels or a fill of a single color in the region specified. * * If the DRM_MODE_FB_DIRTY_ANNOTATE_COPY flag is given then * the number of updated regions are half of num_clips given, * where the clip rects are paired in src and dst. The width and * height of each one of the pairs must match. * * If the DRM_MODE_FB_DIRTY_ANNOTATE_FILL flag is given the caller * promises that the region specified of the clip rects is filled * completely with a single color as given in the color argument. */ struct drm_mode_fb_dirty_cmd { __u32 fb_id; __u32 flags; __u32 color; __u32 num_clips; __u64 clips_ptr; }; struct drm_mode_mode_cmd { __u32 connector_id; struct drm_mode_modeinfo mode; }; #define DRM_MODE_CURSOR_BO 0x01 #define DRM_MODE_CURSOR_MOVE 0x02 #define DRM_MODE_CURSOR_FLAGS 0x03 /* * depending on the value in flags different members are used. * * CURSOR_BO uses * crtc_id * width * height * handle - if 0 turns the cursor off * * CURSOR_MOVE uses * crtc_id * x * y */ struct drm_mode_cursor { __u32 flags; __u32 crtc_id; __s32 x; __s32 y; __u32 width; __u32 height; /* driver specific handle */ __u32 handle; }; struct drm_mode_cursor2 { __u32 flags; __u32 crtc_id; __s32 x; __s32 y; __u32 width; __u32 height; /* driver specific handle */ __u32 handle; __s32 hot_x; __s32 hot_y; }; struct drm_mode_crtc_lut { __u32 crtc_id; __u32 gamma_size; /* pointers to arrays */ __u64 red; __u64 green; __u64 blue; }; struct drm_color_ctm { /* * Conversion matrix in S31.32 sign-magnitude * (not two's complement!) format. */ __u64 matrix[9]; }; struct drm_color_lut { /* * Values are mapped linearly to 0.0 - 1.0 range, with 0x0 == 0.0 and * 0xffff == 1.0. */ __u16 red; __u16 green; __u16 blue; __u16 reserved; }; /** * struct hdr_metadata_infoframe - HDR Metadata Infoframe Data. * * HDR Metadata Infoframe as per CTA 861.G spec. This is expected * to match exactly with the spec. * * Userspace is expected to pass the metadata information as per * the format described in this structure. */ struct hdr_metadata_infoframe { /** * @eotf: Electro-Optical Transfer Function (EOTF) * used in the stream. */ __u8 eotf; /** * @metadata_type: Static_Metadata_Descriptor_ID. */ __u8 metadata_type; /** * @display_primaries: Color Primaries of the Data. * These are coded as unsigned 16-bit values in units of * 0.00002, where 0x0000 represents zero and 0xC350 * represents 1.0000. * @display_primaries.x: X cordinate of color primary. * @display_primaries.y: Y cordinate of color primary. */ struct { __u16 x, y; } display_primaries[3]; /** * @white_point: White Point of Colorspace Data. * These are coded as unsigned 16-bit values in units of * 0.00002, where 0x0000 represents zero and 0xC350 * represents 1.0000. * @white_point.x: X cordinate of whitepoint of color primary. * @white_point.y: Y cordinate of whitepoint of color primary. */ struct { __u16 x, y; } white_point; /** * @max_display_mastering_luminance: Max Mastering Display Luminance. * This value is coded as an unsigned 16-bit value in units of 1 cd/m2, * where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2. */ __u16 max_display_mastering_luminance; /** * @min_display_mastering_luminance: Min Mastering Display Luminance. * This value is coded as an unsigned 16-bit value in units of * 0.0001 cd/m2, where 0x0001 represents 0.0001 cd/m2 and 0xFFFF * represents 6.5535 cd/m2. */ __u16 min_display_mastering_luminance; /** * @max_cll: Max Content Light Level. * This value is coded as an unsigned 16-bit value in units of 1 cd/m2, * where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2. */ __u16 max_cll; /** * @max_fall: Max Frame Average Light Level. * This value is coded as an unsigned 16-bit value in units of 1 cd/m2, * where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2. */ __u16 max_fall; }; /** * struct hdr_output_metadata - HDR output metadata * * Metadata Information to be passed from userspace */ struct hdr_output_metadata { /** * @metadata_type: Static_Metadata_Descriptor_ID. */ __u32 metadata_type; /** * @hdmi_metadata_type1: HDR Metadata Infoframe. */ union { struct hdr_metadata_infoframe hdmi_metadata_type1; }; }; #define DRM_MODE_PAGE_FLIP_EVENT 0x01 #define DRM_MODE_PAGE_FLIP_ASYNC 0x02 #define DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE 0x4 #define DRM_MODE_PAGE_FLIP_TARGET_RELATIVE 0x8 #define DRM_MODE_PAGE_FLIP_TARGET (DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE | \ DRM_MODE_PAGE_FLIP_TARGET_RELATIVE) #define DRM_MODE_PAGE_FLIP_FLAGS (DRM_MODE_PAGE_FLIP_EVENT | \ DRM_MODE_PAGE_FLIP_ASYNC | \ DRM_MODE_PAGE_FLIP_TARGET) /* * Request a page flip on the specified crtc. * * This ioctl will ask KMS to schedule a page flip for the specified * crtc. Once any pending rendering targeting the specified fb (as of * ioctl time) has completed, the crtc will be reprogrammed to display * that fb after the next vertical refresh. The ioctl returns * immediately, but subsequent rendering to the current fb will block * in the execbuffer ioctl until the page flip happens. If a page * flip is already pending as the ioctl is called, EBUSY will be * returned. * * Flag DRM_MODE_PAGE_FLIP_EVENT requests that drm sends back a vblank * event (see drm.h: struct drm_event_vblank) when the page flip is * done. The user_data field passed in with this ioctl will be * returned as the user_data field in the vblank event struct. * * Flag DRM_MODE_PAGE_FLIP_ASYNC requests that the flip happen * 'as soon as possible', meaning that it not delay waiting for vblank. * This may cause tearing on the screen. * * The reserved field must be zero. */ struct drm_mode_crtc_page_flip { __u32 crtc_id; __u32 fb_id; __u32 flags; __u32 reserved; __u64 user_data; }; /* * Request a page flip on the specified crtc. * * Same as struct drm_mode_crtc_page_flip, but supports new flags and * re-purposes the reserved field: * * The sequence field must be zero unless either of the * DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE/RELATIVE flags is specified. When * the ABSOLUTE flag is specified, the sequence field denotes the absolute * vblank sequence when the flip should take effect. When the RELATIVE * flag is specified, the sequence field denotes the relative (to the * current one when the ioctl is called) vblank sequence when the flip * should take effect. NOTE: DRM_IOCTL_WAIT_VBLANK must still be used to * make sure the vblank sequence before the target one has passed before * calling this ioctl. The purpose of the * DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE/RELATIVE flags is merely to clarify * the target for when code dealing with a page flip runs during a * vertical blank period. */ struct drm_mode_crtc_page_flip_target { __u32 crtc_id; __u32 fb_id; __u32 flags; __u32 sequence; __u64 user_data; }; /* create a dumb scanout buffer */ struct drm_mode_create_dumb { __u32 height; __u32 width; __u32 bpp; __u32 flags; /* handle, pitch, size will be returned */ __u32 handle; __u32 pitch; __u64 size; }; /* set up for mmap of a dumb scanout buffer */ struct drm_mode_map_dumb { /** Handle for the object being mapped. */ __u32 handle; __u32 pad; /** * Fake offset to use for subsequent mmap call * * This is a fixed-size type for 32/64 compatibility. */ __u64 offset; }; struct drm_mode_destroy_dumb { __u32 handle; }; /* page-flip flags are valid, plus: */ #define DRM_MODE_ATOMIC_TEST_ONLY 0x0100 #define DRM_MODE_ATOMIC_NONBLOCK 0x0200 #define DRM_MODE_ATOMIC_ALLOW_MODESET 0x0400 #define DRM_MODE_ATOMIC_FLAGS (\ DRM_MODE_PAGE_FLIP_EVENT |\ DRM_MODE_PAGE_FLIP_ASYNC |\ DRM_MODE_ATOMIC_TEST_ONLY |\ DRM_MODE_ATOMIC_NONBLOCK |\ DRM_MODE_ATOMIC_ALLOW_MODESET) struct drm_mode_atomic { __u32 flags; __u32 count_objs; __u64 objs_ptr; __u64 count_props_ptr; __u64 props_ptr; __u64 prop_values_ptr; __u64 reserved; __u64 user_data; }; struct drm_format_modifier_blob { #define FORMAT_BLOB_CURRENT 1 /* Version of this blob format */ __u32 version; /* Flags */ __u32 flags; /* Number of fourcc formats supported */ __u32 count_formats; /* Where in this blob the formats exist (in bytes) */ __u32 formats_offset; /* Number of drm_format_modifiers */ __u32 count_modifiers; /* Where in this blob the modifiers exist (in bytes) */ __u32 modifiers_offset; /* __u32 formats[] */ /* struct drm_format_modifier modifiers[] */ }; struct drm_format_modifier { /* Bitmask of formats in get_plane format list this info applies to. The * offset allows a sliding window of which 64 formats (bits). * * Some examples: * In today's world with < 65 formats, and formats 0, and 2 are * supported * 0x0000000000000005 * ^-offset = 0, formats = 5 * * If the number formats grew to 128, and formats 98-102 are * supported with the modifier: * * 0x0000007c00000000 0000000000000000 * ^ * |__offset = 64, formats = 0x7c00000000 * */ __u64 formats; __u32 offset; __u32 pad; /* The modifier that applies to the >get_plane format list bitmask. */ __u64 modifier; }; /** * struct drm_mode_create_blob - Create New block property * @data: Pointer to data to copy. * @length: Length of data to copy. * @blob_id: new property ID. * Create a new 'blob' data property, copying length bytes from data pointer, * and returning new blob ID. */ struct drm_mode_create_blob { /** Pointer to data to copy. */ __u64 data; /** Length of data to copy. */ __u32 length; /** Return: new property ID. */ __u32 blob_id; }; /** * struct drm_mode_destroy_blob - Destroy user blob * @blob_id: blob_id to destroy * Destroy a user-created blob property. */ struct drm_mode_destroy_blob { __u32 blob_id; }; /** * struct drm_mode_create_lease - Create lease * @object_ids: Pointer to array of object ids. * @object_count: Number of object ids. * @flags: flags for new FD. * @lessee_id: unique identifier for lessee. * @fd: file descriptor to new drm_master file. * Lease mode resources, creating another drm_master. */ struct drm_mode_create_lease { /** Pointer to array of object ids (__u32) */ __u64 object_ids; /** Number of object ids */ __u32 object_count; /** flags for new FD (O_CLOEXEC, etc) */ __u32 flags; /** Return: unique identifier for lessee. */ __u32 lessee_id; /** Return: file descriptor to new drm_master file */ __u32 fd; }; /** * struct drm_mode_list_lessees - List lessees * @count_lessees: Number of lessees. * @pad: pad. * @lessees_ptr: Pointer to lessess. * List lesses from a drm_master */ struct drm_mode_list_lessees { /** Number of lessees. * On input, provides length of the array. * On output, provides total number. No * more than the input number will be written * back, so two calls can be used to get * the size and then the data. */ __u32 count_lessees; __u32 pad; /** Pointer to lessees. * pointer to __u64 array of lessee ids */ __u64 lessees_ptr; }; /** * struct drm_mode_get_lease - Get Lease * @count_objects: Number of leased objects. * @pad: pad. * @objects_ptr: Pointer to objects. * Get leased objects */ struct drm_mode_get_lease { /** Number of leased objects. * On input, provides length of the array. * On output, provides total number. No * more than the input number will be written * back, so two calls can be used to get * the size and then the data. */ __u32 count_objects; __u32 pad; /** Pointer to objects. * pointer to __u32 array of object ids */ __u64 objects_ptr; }; /** * struct drm_mode_revoke_lease - Revoke lease * @lessee_id: Unique ID of lessee. * Revoke lease */ struct drm_mode_revoke_lease { /** Unique ID of lessee */ __u32 lessee_id; }; /** * struct drm_mode_rect - Two dimensional rectangle. * @x1: Horizontal starting coordinate (inclusive). * @y1: Vertical starting coordinate (inclusive). * @x2: Horizontal ending coordinate (exclusive). * @y2: Vertical ending coordinate (exclusive). * * With drm subsystem using struct drm_rect to manage rectangular area this * export it to user-space. * * Currently used by drm_mode_atomic blob property FB_DAMAGE_CLIPS. */ struct drm_mode_rect { __s32 x1; __s32 y1; __s32 x2; __s32 y2; }; #if defined(__cplusplus) } #endif #endif ================================================ FILE: mesa/include/drm-uapi/i915_drm.h ================================================ /* * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #ifndef _I915_DRM_H_ #define _I915_DRM_H_ #include "drm.h" #if defined(__cplusplus) extern "C" { #endif /* Please note that modifications to all structs defined here are * subject to backwards-compatibility constraints. */ /** * DOC: uevents generated by i915 on it's device node * * I915_L3_PARITY_UEVENT - Generated when the driver receives a parity mismatch * event from the gpu l3 cache. Additional information supplied is ROW, * BANK, SUBBANK, SLICE of the affected cacheline. Userspace should keep * track of these events and if a specific cache-line seems to have a * persistent error remap it with the l3 remapping tool supplied in * intel-gpu-tools. The value supplied with the event is always 1. * * I915_ERROR_UEVENT - Generated upon error detection, currently only via * hangcheck. The error detection event is a good indicator of when things * began to go badly. The value supplied with the event is a 1 upon error * detection, and a 0 upon reset completion, signifying no more error * exists. NOTE: Disabling hangcheck or reset via module parameter will * cause the related events to not be seen. * * I915_RESET_UEVENT - Event is generated just before an attempt to reset the * the GPU. The value supplied with the event is always 1. NOTE: Disable * reset via module parameter will cause this event to not be seen. */ #define I915_L3_PARITY_UEVENT "L3_PARITY_ERROR" #define I915_ERROR_UEVENT "ERROR" #define I915_RESET_UEVENT "RESET" /* * i915_user_extension: Base class for defining a chain of extensions * * Many interfaces need to grow over time. In most cases we can simply * extend the struct and have userspace pass in more data. Another option, * as demonstrated by Vulkan's approach to providing extensions for forward * and backward compatibility, is to use a list of optional structs to * provide those extra details. * * The key advantage to using an extension chain is that it allows us to * redefine the interface more easily than an ever growing struct of * increasing complexity, and for large parts of that interface to be * entirely optional. The downside is more pointer chasing; chasing across * the boundary with pointers encapsulated inside u64. */ struct i915_user_extension { __u64 next_extension; __u32 name; __u32 flags; /* All undefined bits must be zero. */ __u32 rsvd[4]; /* Reserved for future use; must be zero. */ }; /* * MOCS indexes used for GPU surfaces, defining the cacheability of the * surface data and the coherency for this data wrt. CPU vs. GPU accesses. */ enum i915_mocs_table_index { /* * Not cached anywhere, coherency between CPU and GPU accesses is * guaranteed. */ I915_MOCS_UNCACHED, /* * Cacheability and coherency controlled by the kernel automatically * based on the DRM_I915_GEM_SET_CACHING IOCTL setting and the current * usage of the surface (used for display scanout or not). */ I915_MOCS_PTE, /* * Cached in all GPU caches available on the platform. * Coherency between CPU and GPU accesses to the surface is not * guaranteed without extra synchronization. */ I915_MOCS_CACHED, }; /* * Different engines serve different roles, and there may be more than one * engine serving each role. enum drm_i915_gem_engine_class provides a * classification of the role of the engine, which may be used when requesting * operations to be performed on a certain subset of engines, or for providing * information about that group. */ enum drm_i915_gem_engine_class { I915_ENGINE_CLASS_RENDER = 0, I915_ENGINE_CLASS_COPY = 1, I915_ENGINE_CLASS_VIDEO = 2, I915_ENGINE_CLASS_VIDEO_ENHANCE = 3, /* should be kept compact */ I915_ENGINE_CLASS_INVALID = -1 }; /* * There may be more than one engine fulfilling any role within the system. * Each engine of a class is given a unique instance number and therefore * any engine can be specified by its class:instance tuplet. APIs that allow * access to any engine in the system will use struct i915_engine_class_instance * for this identification. */ struct i915_engine_class_instance { __u16 engine_class; /* see enum drm_i915_gem_engine_class */ __u16 engine_instance; #define I915_ENGINE_CLASS_INVALID_NONE -1 #define I915_ENGINE_CLASS_INVALID_VIRTUAL -2 }; /** * DOC: perf_events exposed by i915 through /sys/bus/event_sources/drivers/i915 * */ enum drm_i915_pmu_engine_sample { I915_SAMPLE_BUSY = 0, I915_SAMPLE_WAIT = 1, I915_SAMPLE_SEMA = 2 }; #define I915_PMU_SAMPLE_BITS (4) #define I915_PMU_SAMPLE_MASK (0xf) #define I915_PMU_SAMPLE_INSTANCE_BITS (8) #define I915_PMU_CLASS_SHIFT \ (I915_PMU_SAMPLE_BITS + I915_PMU_SAMPLE_INSTANCE_BITS) #define __I915_PMU_ENGINE(class, instance, sample) \ ((class) << I915_PMU_CLASS_SHIFT | \ (instance) << I915_PMU_SAMPLE_BITS | \ (sample)) #define I915_PMU_ENGINE_BUSY(class, instance) \ __I915_PMU_ENGINE(class, instance, I915_SAMPLE_BUSY) #define I915_PMU_ENGINE_WAIT(class, instance) \ __I915_PMU_ENGINE(class, instance, I915_SAMPLE_WAIT) #define I915_PMU_ENGINE_SEMA(class, instance) \ __I915_PMU_ENGINE(class, instance, I915_SAMPLE_SEMA) #define __I915_PMU_OTHER(x) (__I915_PMU_ENGINE(0xff, 0xff, 0xf) + 1 + (x)) #define I915_PMU_ACTUAL_FREQUENCY __I915_PMU_OTHER(0) #define I915_PMU_REQUESTED_FREQUENCY __I915_PMU_OTHER(1) #define I915_PMU_INTERRUPTS __I915_PMU_OTHER(2) #define I915_PMU_RC6_RESIDENCY __I915_PMU_OTHER(3) #define I915_PMU_LAST I915_PMU_RC6_RESIDENCY /* Each region is a minimum of 16k, and there are at most 255 of them. */ #define I915_NR_TEX_REGIONS 255 /* table size 2k - maximum due to use * of chars for next/prev indices */ #define I915_LOG_MIN_TEX_REGION_SIZE 14 typedef struct _drm_i915_init { enum { I915_INIT_DMA = 0x01, I915_CLEANUP_DMA = 0x02, I915_RESUME_DMA = 0x03 } func; unsigned int mmio_offset; int sarea_priv_offset; unsigned int ring_start; unsigned int ring_end; unsigned int ring_size; unsigned int front_offset; unsigned int back_offset; unsigned int depth_offset; unsigned int w; unsigned int h; unsigned int pitch; unsigned int pitch_bits; unsigned int back_pitch; unsigned int depth_pitch; unsigned int cpp; unsigned int chipset; } drm_i915_init_t; typedef struct _drm_i915_sarea { struct drm_tex_region texList[I915_NR_TEX_REGIONS + 1]; int last_upload; /* last time texture was uploaded */ int last_enqueue; /* last time a buffer was enqueued */ int last_dispatch; /* age of the most recently dispatched buffer */ int ctxOwner; /* last context to upload state */ int texAge; int pf_enabled; /* is pageflipping allowed? */ int pf_active; int pf_current_page; /* which buffer is being displayed? */ int perf_boxes; /* performance boxes to be displayed */ int width, height; /* screen size in pixels */ drm_handle_t front_handle; int front_offset; int front_size; drm_handle_t back_handle; int back_offset; int back_size; drm_handle_t depth_handle; int depth_offset; int depth_size; drm_handle_t tex_handle; int tex_offset; int tex_size; int log_tex_granularity; int pitch; int rotation; /* 0, 90, 180 or 270 */ int rotated_offset; int rotated_size; int rotated_pitch; int virtualX, virtualY; unsigned int front_tiled; unsigned int back_tiled; unsigned int depth_tiled; unsigned int rotated_tiled; unsigned int rotated2_tiled; int pipeA_x; int pipeA_y; int pipeA_w; int pipeA_h; int pipeB_x; int pipeB_y; int pipeB_w; int pipeB_h; /* fill out some space for old userspace triple buffer */ drm_handle_t unused_handle; __u32 unused1, unused2, unused3; /* buffer object handles for static buffers. May change * over the lifetime of the client. */ __u32 front_bo_handle; __u32 back_bo_handle; __u32 unused_bo_handle; __u32 depth_bo_handle; } drm_i915_sarea_t; /* due to userspace building against these headers we need some compat here */ #define planeA_x pipeA_x #define planeA_y pipeA_y #define planeA_w pipeA_w #define planeA_h pipeA_h #define planeB_x pipeB_x #define planeB_y pipeB_y #define planeB_w pipeB_w #define planeB_h pipeB_h /* Flags for perf_boxes */ #define I915_BOX_RING_EMPTY 0x1 #define I915_BOX_FLIP 0x2 #define I915_BOX_WAIT 0x4 #define I915_BOX_TEXTURE_LOAD 0x8 #define I915_BOX_LOST_CONTEXT 0x10 /* * i915 specific ioctls. * * The device specific ioctl range is [DRM_COMMAND_BASE, DRM_COMMAND_END) ie * [0x40, 0xa0) (a0 is excluded). The numbers below are defined as offset * against DRM_COMMAND_BASE and should be between [0x0, 0x60). */ #define DRM_I915_INIT 0x00 #define DRM_I915_FLUSH 0x01 #define DRM_I915_FLIP 0x02 #define DRM_I915_BATCHBUFFER 0x03 #define DRM_I915_IRQ_EMIT 0x04 #define DRM_I915_IRQ_WAIT 0x05 #define DRM_I915_GETPARAM 0x06 #define DRM_I915_SETPARAM 0x07 #define DRM_I915_ALLOC 0x08 #define DRM_I915_FREE 0x09 #define DRM_I915_INIT_HEAP 0x0a #define DRM_I915_CMDBUFFER 0x0b #define DRM_I915_DESTROY_HEAP 0x0c #define DRM_I915_SET_VBLANK_PIPE 0x0d #define DRM_I915_GET_VBLANK_PIPE 0x0e #define DRM_I915_VBLANK_SWAP 0x0f #define DRM_I915_HWS_ADDR 0x11 #define DRM_I915_GEM_INIT 0x13 #define DRM_I915_GEM_EXECBUFFER 0x14 #define DRM_I915_GEM_PIN 0x15 #define DRM_I915_GEM_UNPIN 0x16 #define DRM_I915_GEM_BUSY 0x17 #define DRM_I915_GEM_THROTTLE 0x18 #define DRM_I915_GEM_ENTERVT 0x19 #define DRM_I915_GEM_LEAVEVT 0x1a #define DRM_I915_GEM_CREATE 0x1b #define DRM_I915_GEM_PREAD 0x1c #define DRM_I915_GEM_PWRITE 0x1d #define DRM_I915_GEM_MMAP 0x1e #define DRM_I915_GEM_SET_DOMAIN 0x1f #define DRM_I915_GEM_SW_FINISH 0x20 #define DRM_I915_GEM_SET_TILING 0x21 #define DRM_I915_GEM_GET_TILING 0x22 #define DRM_I915_GEM_GET_APERTURE 0x23 #define DRM_I915_GEM_MMAP_GTT 0x24 #define DRM_I915_GET_PIPE_FROM_CRTC_ID 0x25 #define DRM_I915_GEM_MADVISE 0x26 #define DRM_I915_OVERLAY_PUT_IMAGE 0x27 #define DRM_I915_OVERLAY_ATTRS 0x28 #define DRM_I915_GEM_EXECBUFFER2 0x29 #define DRM_I915_GEM_EXECBUFFER2_WR DRM_I915_GEM_EXECBUFFER2 #define DRM_I915_GET_SPRITE_COLORKEY 0x2a #define DRM_I915_SET_SPRITE_COLORKEY 0x2b #define DRM_I915_GEM_WAIT 0x2c #define DRM_I915_GEM_CONTEXT_CREATE 0x2d #define DRM_I915_GEM_CONTEXT_DESTROY 0x2e #define DRM_I915_GEM_SET_CACHING 0x2f #define DRM_I915_GEM_GET_CACHING 0x30 #define DRM_I915_REG_READ 0x31 #define DRM_I915_GET_RESET_STATS 0x32 #define DRM_I915_GEM_USERPTR 0x33 #define DRM_I915_GEM_CONTEXT_GETPARAM 0x34 #define DRM_I915_GEM_CONTEXT_SETPARAM 0x35 #define DRM_I915_PERF_OPEN 0x36 #define DRM_I915_PERF_ADD_CONFIG 0x37 #define DRM_I915_PERF_REMOVE_CONFIG 0x38 #define DRM_I915_QUERY 0x39 #define DRM_I915_GEM_VM_CREATE 0x3a #define DRM_I915_GEM_VM_DESTROY 0x3b /* Must be kept compact -- no holes */ #define DRM_IOCTL_I915_INIT DRM_IOW( DRM_COMMAND_BASE + DRM_I915_INIT, drm_i915_init_t) #define DRM_IOCTL_I915_FLUSH DRM_IO ( DRM_COMMAND_BASE + DRM_I915_FLUSH) #define DRM_IOCTL_I915_FLIP DRM_IO ( DRM_COMMAND_BASE + DRM_I915_FLIP) #define DRM_IOCTL_I915_BATCHBUFFER DRM_IOW( DRM_COMMAND_BASE + DRM_I915_BATCHBUFFER, drm_i915_batchbuffer_t) #define DRM_IOCTL_I915_IRQ_EMIT DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_IRQ_EMIT, drm_i915_irq_emit_t) #define DRM_IOCTL_I915_IRQ_WAIT DRM_IOW( DRM_COMMAND_BASE + DRM_I915_IRQ_WAIT, drm_i915_irq_wait_t) #define DRM_IOCTL_I915_GETPARAM DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GETPARAM, drm_i915_getparam_t) #define DRM_IOCTL_I915_SETPARAM DRM_IOW( DRM_COMMAND_BASE + DRM_I915_SETPARAM, drm_i915_setparam_t) #define DRM_IOCTL_I915_ALLOC DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_ALLOC, drm_i915_mem_alloc_t) #define DRM_IOCTL_I915_FREE DRM_IOW( DRM_COMMAND_BASE + DRM_I915_FREE, drm_i915_mem_free_t) #define DRM_IOCTL_I915_INIT_HEAP DRM_IOW( DRM_COMMAND_BASE + DRM_I915_INIT_HEAP, drm_i915_mem_init_heap_t) #define DRM_IOCTL_I915_CMDBUFFER DRM_IOW( DRM_COMMAND_BASE + DRM_I915_CMDBUFFER, drm_i915_cmdbuffer_t) #define DRM_IOCTL_I915_DESTROY_HEAP DRM_IOW( DRM_COMMAND_BASE + DRM_I915_DESTROY_HEAP, drm_i915_mem_destroy_heap_t) #define DRM_IOCTL_I915_SET_VBLANK_PIPE DRM_IOW( DRM_COMMAND_BASE + DRM_I915_SET_VBLANK_PIPE, drm_i915_vblank_pipe_t) #define DRM_IOCTL_I915_GET_VBLANK_PIPE DRM_IOR( DRM_COMMAND_BASE + DRM_I915_GET_VBLANK_PIPE, drm_i915_vblank_pipe_t) #define DRM_IOCTL_I915_VBLANK_SWAP DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_VBLANK_SWAP, drm_i915_vblank_swap_t) #define DRM_IOCTL_I915_HWS_ADDR DRM_IOW(DRM_COMMAND_BASE + DRM_I915_HWS_ADDR, struct drm_i915_gem_init) #define DRM_IOCTL_I915_GEM_INIT DRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_INIT, struct drm_i915_gem_init) #define DRM_IOCTL_I915_GEM_EXECBUFFER DRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_EXECBUFFER, struct drm_i915_gem_execbuffer) #define DRM_IOCTL_I915_GEM_EXECBUFFER2 DRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_EXECBUFFER2, struct drm_i915_gem_execbuffer2) #define DRM_IOCTL_I915_GEM_EXECBUFFER2_WR DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_EXECBUFFER2_WR, struct drm_i915_gem_execbuffer2) #define DRM_IOCTL_I915_GEM_PIN DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_PIN, struct drm_i915_gem_pin) #define DRM_IOCTL_I915_GEM_UNPIN DRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_UNPIN, struct drm_i915_gem_unpin) #define DRM_IOCTL_I915_GEM_BUSY DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_BUSY, struct drm_i915_gem_busy) #define DRM_IOCTL_I915_GEM_SET_CACHING DRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_SET_CACHING, struct drm_i915_gem_caching) #define DRM_IOCTL_I915_GEM_GET_CACHING DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_GET_CACHING, struct drm_i915_gem_caching) #define DRM_IOCTL_I915_GEM_THROTTLE DRM_IO ( DRM_COMMAND_BASE + DRM_I915_GEM_THROTTLE) #define DRM_IOCTL_I915_GEM_ENTERVT DRM_IO(DRM_COMMAND_BASE + DRM_I915_GEM_ENTERVT) #define DRM_IOCTL_I915_GEM_LEAVEVT DRM_IO(DRM_COMMAND_BASE + DRM_I915_GEM_LEAVEVT) #define DRM_IOCTL_I915_GEM_CREATE DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_CREATE, struct drm_i915_gem_create) #define DRM_IOCTL_I915_GEM_PREAD DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_PREAD, struct drm_i915_gem_pread) #define DRM_IOCTL_I915_GEM_PWRITE DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_PWRITE, struct drm_i915_gem_pwrite) #define DRM_IOCTL_I915_GEM_MMAP DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MMAP, struct drm_i915_gem_mmap) #define DRM_IOCTL_I915_GEM_MMAP_GTT DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MMAP_GTT, struct drm_i915_gem_mmap_gtt) #define DRM_IOCTL_I915_GEM_SET_DOMAIN DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_SET_DOMAIN, struct drm_i915_gem_set_domain) #define DRM_IOCTL_I915_GEM_SW_FINISH DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_SW_FINISH, struct drm_i915_gem_sw_finish) #define DRM_IOCTL_I915_GEM_SET_TILING DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_SET_TILING, struct drm_i915_gem_set_tiling) #define DRM_IOCTL_I915_GEM_GET_TILING DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_GET_TILING, struct drm_i915_gem_get_tiling) #define DRM_IOCTL_I915_GEM_GET_APERTURE DRM_IOR (DRM_COMMAND_BASE + DRM_I915_GEM_GET_APERTURE, struct drm_i915_gem_get_aperture) #define DRM_IOCTL_I915_GET_PIPE_FROM_CRTC_ID DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GET_PIPE_FROM_CRTC_ID, struct drm_i915_get_pipe_from_crtc_id) #define DRM_IOCTL_I915_GEM_MADVISE DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MADVISE, struct drm_i915_gem_madvise) #define DRM_IOCTL_I915_OVERLAY_PUT_IMAGE DRM_IOW(DRM_COMMAND_BASE + DRM_I915_OVERLAY_PUT_IMAGE, struct drm_intel_overlay_put_image) #define DRM_IOCTL_I915_OVERLAY_ATTRS DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_OVERLAY_ATTRS, struct drm_intel_overlay_attrs) #define DRM_IOCTL_I915_SET_SPRITE_COLORKEY DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_SET_SPRITE_COLORKEY, struct drm_intel_sprite_colorkey) #define DRM_IOCTL_I915_GET_SPRITE_COLORKEY DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GET_SPRITE_COLORKEY, struct drm_intel_sprite_colorkey) #define DRM_IOCTL_I915_GEM_WAIT DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_WAIT, struct drm_i915_gem_wait) #define DRM_IOCTL_I915_GEM_CONTEXT_CREATE DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_CREATE, struct drm_i915_gem_context_create) #define DRM_IOCTL_I915_GEM_CONTEXT_CREATE_EXT DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_CREATE, struct drm_i915_gem_context_create_ext) #define DRM_IOCTL_I915_GEM_CONTEXT_DESTROY DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_DESTROY, struct drm_i915_gem_context_destroy) #define DRM_IOCTL_I915_REG_READ DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_REG_READ, struct drm_i915_reg_read) #define DRM_IOCTL_I915_GET_RESET_STATS DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GET_RESET_STATS, struct drm_i915_reset_stats) #define DRM_IOCTL_I915_GEM_USERPTR DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_USERPTR, struct drm_i915_gem_userptr) #define DRM_IOCTL_I915_GEM_CONTEXT_GETPARAM DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_GETPARAM, struct drm_i915_gem_context_param) #define DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_SETPARAM, struct drm_i915_gem_context_param) #define DRM_IOCTL_I915_PERF_OPEN DRM_IOW(DRM_COMMAND_BASE + DRM_I915_PERF_OPEN, struct drm_i915_perf_open_param) #define DRM_IOCTL_I915_PERF_ADD_CONFIG DRM_IOW(DRM_COMMAND_BASE + DRM_I915_PERF_ADD_CONFIG, struct drm_i915_perf_oa_config) #define DRM_IOCTL_I915_PERF_REMOVE_CONFIG DRM_IOW(DRM_COMMAND_BASE + DRM_I915_PERF_REMOVE_CONFIG, __u64) #define DRM_IOCTL_I915_QUERY DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_QUERY, struct drm_i915_query) #define DRM_IOCTL_I915_GEM_VM_CREATE DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_VM_CREATE, struct drm_i915_gem_vm_control) #define DRM_IOCTL_I915_GEM_VM_DESTROY DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_VM_DESTROY, struct drm_i915_gem_vm_control) /* Allow drivers to submit batchbuffers directly to hardware, relying * on the security mechanisms provided by hardware. */ typedef struct drm_i915_batchbuffer { int start; /* agp offset */ int used; /* nr bytes in use */ int DR1; /* hw flags for GFX_OP_DRAWRECT_INFO */ int DR4; /* window origin for GFX_OP_DRAWRECT_INFO */ int num_cliprects; /* mulitpass with multiple cliprects? */ struct drm_clip_rect *cliprects; /* pointer to userspace cliprects */ } drm_i915_batchbuffer_t; /* As above, but pass a pointer to userspace buffer which can be * validated by the kernel prior to sending to hardware. */ typedef struct _drm_i915_cmdbuffer { char *buf; /* pointer to userspace command buffer */ int sz; /* nr bytes in buf */ int DR1; /* hw flags for GFX_OP_DRAWRECT_INFO */ int DR4; /* window origin for GFX_OP_DRAWRECT_INFO */ int num_cliprects; /* mulitpass with multiple cliprects? */ struct drm_clip_rect *cliprects; /* pointer to userspace cliprects */ } drm_i915_cmdbuffer_t; /* Userspace can request & wait on irq's: */ typedef struct drm_i915_irq_emit { int *irq_seq; } drm_i915_irq_emit_t; typedef struct drm_i915_irq_wait { int irq_seq; } drm_i915_irq_wait_t; /* * Different modes of per-process Graphics Translation Table, * see I915_PARAM_HAS_ALIASING_PPGTT */ #define I915_GEM_PPGTT_NONE 0 #define I915_GEM_PPGTT_ALIASING 1 #define I915_GEM_PPGTT_FULL 2 /* Ioctl to query kernel params: */ #define I915_PARAM_IRQ_ACTIVE 1 #define I915_PARAM_ALLOW_BATCHBUFFER 2 #define I915_PARAM_LAST_DISPATCH 3 #define I915_PARAM_CHIPSET_ID 4 #define I915_PARAM_HAS_GEM 5 #define I915_PARAM_NUM_FENCES_AVAIL 6 #define I915_PARAM_HAS_OVERLAY 7 #define I915_PARAM_HAS_PAGEFLIPPING 8 #define I915_PARAM_HAS_EXECBUF2 9 #define I915_PARAM_HAS_BSD 10 #define I915_PARAM_HAS_BLT 11 #define I915_PARAM_HAS_RELAXED_FENCING 12 #define I915_PARAM_HAS_COHERENT_RINGS 13 #define I915_PARAM_HAS_EXEC_CONSTANTS 14 #define I915_PARAM_HAS_RELAXED_DELTA 15 #define I915_PARAM_HAS_GEN7_SOL_RESET 16 #define I915_PARAM_HAS_LLC 17 #define I915_PARAM_HAS_ALIASING_PPGTT 18 #define I915_PARAM_HAS_WAIT_TIMEOUT 19 #define I915_PARAM_HAS_SEMAPHORES 20 #define I915_PARAM_HAS_PRIME_VMAP_FLUSH 21 #define I915_PARAM_HAS_VEBOX 22 #define I915_PARAM_HAS_SECURE_BATCHES 23 #define I915_PARAM_HAS_PINNED_BATCHES 24 #define I915_PARAM_HAS_EXEC_NO_RELOC 25 #define I915_PARAM_HAS_EXEC_HANDLE_LUT 26 #define I915_PARAM_HAS_WT 27 #define I915_PARAM_CMD_PARSER_VERSION 28 #define I915_PARAM_HAS_COHERENT_PHYS_GTT 29 #define I915_PARAM_MMAP_VERSION 30 #define I915_PARAM_HAS_BSD2 31 #define I915_PARAM_REVISION 32 #define I915_PARAM_SUBSLICE_TOTAL 33 #define I915_PARAM_EU_TOTAL 34 #define I915_PARAM_HAS_GPU_RESET 35 #define I915_PARAM_HAS_RESOURCE_STREAMER 36 #define I915_PARAM_HAS_EXEC_SOFTPIN 37 #define I915_PARAM_HAS_POOLED_EU 38 #define I915_PARAM_MIN_EU_IN_POOL 39 #define I915_PARAM_MMAP_GTT_VERSION 40 /* * Query whether DRM_I915_GEM_EXECBUFFER2 supports user defined execution * priorities and the driver will attempt to execute batches in priority order. * The param returns a capability bitmask, nonzero implies that the scheduler * is enabled, with different features present according to the mask. * * The initial priority for each batch is supplied by the context and is * controlled via I915_CONTEXT_PARAM_PRIORITY. */ #define I915_PARAM_HAS_SCHEDULER 41 #define I915_SCHEDULER_CAP_ENABLED (1ul << 0) #define I915_SCHEDULER_CAP_PRIORITY (1ul << 1) #define I915_SCHEDULER_CAP_PREEMPTION (1ul << 2) #define I915_SCHEDULER_CAP_SEMAPHORES (1ul << 3) #define I915_SCHEDULER_CAP_ENGINE_BUSY_STATS (1ul << 4) #define I915_PARAM_HUC_STATUS 42 /* Query whether DRM_I915_GEM_EXECBUFFER2 supports the ability to opt-out of * synchronisation with implicit fencing on individual objects. * See EXEC_OBJECT_ASYNC. */ #define I915_PARAM_HAS_EXEC_ASYNC 43 /* Query whether DRM_I915_GEM_EXECBUFFER2 supports explicit fence support - * both being able to pass in a sync_file fd to wait upon before executing, * and being able to return a new sync_file fd that is signaled when the * current request is complete. See I915_EXEC_FENCE_IN and I915_EXEC_FENCE_OUT. */ #define I915_PARAM_HAS_EXEC_FENCE 44 /* Query whether DRM_I915_GEM_EXECBUFFER2 supports the ability to capture * user specified bufffers for post-mortem debugging of GPU hangs. See * EXEC_OBJECT_CAPTURE. */ #define I915_PARAM_HAS_EXEC_CAPTURE 45 #define I915_PARAM_SLICE_MASK 46 /* Assuming it's uniform for each slice, this queries the mask of subslices * per-slice for this system. */ #define I915_PARAM_SUBSLICE_MASK 47 /* * Query whether DRM_I915_GEM_EXECBUFFER2 supports supplying the batch buffer * as the first execobject as opposed to the last. See I915_EXEC_BATCH_FIRST. */ #define I915_PARAM_HAS_EXEC_BATCH_FIRST 48 /* Query whether DRM_I915_GEM_EXECBUFFER2 supports supplying an array of * drm_i915_gem_exec_fence structures. See I915_EXEC_FENCE_ARRAY. */ #define I915_PARAM_HAS_EXEC_FENCE_ARRAY 49 /* * Query whether every context (both per-file default and user created) is * isolated (insofar as HW supports). If this parameter is not true, then * freshly created contexts may inherit values from an existing context, * rather than default HW values. If true, it also ensures (insofar as HW * supports) that all state set by this context will not leak to any other * context. * * As not every engine across every gen support contexts, the returned * value reports the support of context isolation for individual engines by * returning a bitmask of each engine class set to true if that class supports * isolation. */ #define I915_PARAM_HAS_CONTEXT_ISOLATION 50 /* Frequency of the command streamer timestamps given by the *_TIMESTAMP * registers. This used to be fixed per platform but from CNL onwards, this * might vary depending on the parts. */ #define I915_PARAM_CS_TIMESTAMP_FREQUENCY 51 /* * Once upon a time we supposed that writes through the GGTT would be * immediately in physical memory (once flushed out of the CPU path). However, * on a few different processors and chipsets, this is not necessarily the case * as the writes appear to be buffered internally. Thus a read of the backing * storage (physical memory) via a different path (with different physical tags * to the indirect write via the GGTT) will see stale values from before * the GGTT write. Inside the kernel, we can for the most part keep track of * the different read/write domains in use (e.g. set-domain), but the assumption * of coherency is baked into the ABI, hence reporting its true state in this * parameter. * * Reports true when writes via mmap_gtt are immediately visible following an * lfence to flush the WCB. * * Reports false when writes via mmap_gtt are indeterminately delayed in an in * internal buffer and are _not_ immediately visible to third parties accessing * directly via mmap_cpu/mmap_wc. Use of mmap_gtt as part of an IPC * communications channel when reporting false is strongly disadvised. */ #define I915_PARAM_MMAP_GTT_COHERENT 52 /* * Query whether DRM_I915_GEM_EXECBUFFER2 supports coordination of parallel * execution through use of explicit fence support. * See I915_EXEC_FENCE_OUT and I915_EXEC_FENCE_SUBMIT. */ #define I915_PARAM_HAS_EXEC_SUBMIT_FENCE 53 /* * Revision of the i915-perf uAPI. The value returned helps determine what * i915-perf features are available. See drm_i915_perf_property_id. */ #define I915_PARAM_PERF_REVISION 54 /* Must be kept compact -- no holes and well documented */ typedef struct drm_i915_getparam { __s32 param; /* * WARNING: Using pointers instead of fixed-size u64 means we need to write * compat32 code. Don't repeat this mistake. */ int *value; } drm_i915_getparam_t; /* Ioctl to set kernel params: */ #define I915_SETPARAM_USE_MI_BATCHBUFFER_START 1 #define I915_SETPARAM_TEX_LRU_LOG_GRANULARITY 2 #define I915_SETPARAM_ALLOW_BATCHBUFFER 3 #define I915_SETPARAM_NUM_USED_FENCES 4 /* Must be kept compact -- no holes */ typedef struct drm_i915_setparam { int param; int value; } drm_i915_setparam_t; /* A memory manager for regions of shared memory: */ #define I915_MEM_REGION_AGP 1 typedef struct drm_i915_mem_alloc { int region; int alignment; int size; int *region_offset; /* offset from start of fb or agp */ } drm_i915_mem_alloc_t; typedef struct drm_i915_mem_free { int region; int region_offset; } drm_i915_mem_free_t; typedef struct drm_i915_mem_init_heap { int region; int size; int start; } drm_i915_mem_init_heap_t; /* Allow memory manager to be torn down and re-initialized (eg on * rotate): */ typedef struct drm_i915_mem_destroy_heap { int region; } drm_i915_mem_destroy_heap_t; /* Allow X server to configure which pipes to monitor for vblank signals */ #define DRM_I915_VBLANK_PIPE_A 1 #define DRM_I915_VBLANK_PIPE_B 2 typedef struct drm_i915_vblank_pipe { int pipe; } drm_i915_vblank_pipe_t; /* Schedule buffer swap at given vertical blank: */ typedef struct drm_i915_vblank_swap { drm_drawable_t drawable; enum drm_vblank_seq_type seqtype; unsigned int sequence; } drm_i915_vblank_swap_t; typedef struct drm_i915_hws_addr { __u64 addr; } drm_i915_hws_addr_t; struct drm_i915_gem_init { /** * Beginning offset in the GTT to be managed by the DRM memory * manager. */ __u64 gtt_start; /** * Ending offset in the GTT to be managed by the DRM memory * manager. */ __u64 gtt_end; }; struct drm_i915_gem_create { /** * Requested size for the object. * * The (page-aligned) allocated size for the object will be returned. */ __u64 size; /** * Returned handle for the object. * * Object handles are nonzero. */ __u32 handle; __u32 pad; }; struct drm_i915_gem_pread { /** Handle for the object being read. */ __u32 handle; __u32 pad; /** Offset into the object to read from */ __u64 offset; /** Length of data to read */ __u64 size; /** * Pointer to write the data into. * * This is a fixed-size type for 32/64 compatibility. */ __u64 data_ptr; }; struct drm_i915_gem_pwrite { /** Handle for the object being written to. */ __u32 handle; __u32 pad; /** Offset into the object to write to */ __u64 offset; /** Length of data to write */ __u64 size; /** * Pointer to read the data from. * * This is a fixed-size type for 32/64 compatibility. */ __u64 data_ptr; }; struct drm_i915_gem_mmap { /** Handle for the object being mapped. */ __u32 handle; __u32 pad; /** Offset in the object to map. */ __u64 offset; /** * Length of data to map. * * The value will be page-aligned. */ __u64 size; /** * Returned pointer the data was mapped at. * * This is a fixed-size type for 32/64 compatibility. */ __u64 addr_ptr; /** * Flags for extended behaviour. * * Added in version 2. */ __u64 flags; #define I915_MMAP_WC 0x1 }; struct drm_i915_gem_mmap_gtt { /** Handle for the object being mapped. */ __u32 handle; __u32 pad; /** * Fake offset to use for subsequent mmap call * * This is a fixed-size type for 32/64 compatibility. */ __u64 offset; }; struct drm_i915_gem_set_domain { /** Handle for the object */ __u32 handle; /** New read domains */ __u32 read_domains; /** New write domain */ __u32 write_domain; }; struct drm_i915_gem_sw_finish { /** Handle for the object */ __u32 handle; }; struct drm_i915_gem_relocation_entry { /** * Handle of the buffer being pointed to by this relocation entry. * * It's appealing to make this be an index into the mm_validate_entry * list to refer to the buffer, but this allows the driver to create * a relocation list for state buffers and not re-write it per * exec using the buffer. */ __u32 target_handle; /** * Value to be added to the offset of the target buffer to make up * the relocation entry. */ __u32 delta; /** Offset in the buffer the relocation entry will be written into */ __u64 offset; /** * Offset value of the target buffer that the relocation entry was last * written as. * * If the buffer has the same offset as last time, we can skip syncing * and writing the relocation. This value is written back out by * the execbuffer ioctl when the relocation is written. */ __u64 presumed_offset; /** * Target memory domains read by this operation. */ __u32 read_domains; /** * Target memory domains written by this operation. * * Note that only one domain may be written by the whole * execbuffer operation, so that where there are conflicts, * the application will get -EINVAL back. */ __u32 write_domain; }; /** @{ * Intel memory domains * * Most of these just align with the various caches in * the system and are used to flush and invalidate as * objects end up cached in different domains. */ /** CPU cache */ #define I915_GEM_DOMAIN_CPU 0x00000001 /** Render cache, used by 2D and 3D drawing */ #define I915_GEM_DOMAIN_RENDER 0x00000002 /** Sampler cache, used by texture engine */ #define I915_GEM_DOMAIN_SAMPLER 0x00000004 /** Command queue, used to load batch buffers */ #define I915_GEM_DOMAIN_COMMAND 0x00000008 /** Instruction cache, used by shader programs */ #define I915_GEM_DOMAIN_INSTRUCTION 0x00000010 /** Vertex address cache */ #define I915_GEM_DOMAIN_VERTEX 0x00000020 /** GTT domain - aperture and scanout */ #define I915_GEM_DOMAIN_GTT 0x00000040 /** WC domain - uncached access */ #define I915_GEM_DOMAIN_WC 0x00000080 /** @} */ struct drm_i915_gem_exec_object { /** * User's handle for a buffer to be bound into the GTT for this * operation. */ __u32 handle; /** Number of relocations to be performed on this buffer */ __u32 relocation_count; /** * Pointer to array of struct drm_i915_gem_relocation_entry containing * the relocations to be performed in this buffer. */ __u64 relocs_ptr; /** Required alignment in graphics aperture */ __u64 alignment; /** * Returned value of the updated offset of the object, for future * presumed_offset writes. */ __u64 offset; }; struct drm_i915_gem_execbuffer { /** * List of buffers to be validated with their relocations to be * performend on them. * * This is a pointer to an array of struct drm_i915_gem_validate_entry. * * These buffers must be listed in an order such that all relocations * a buffer is performing refer to buffers that have already appeared * in the validate list. */ __u64 buffers_ptr; __u32 buffer_count; /** Offset in the batchbuffer to start execution from. */ __u32 batch_start_offset; /** Bytes used in batchbuffer from batch_start_offset */ __u32 batch_len; __u32 DR1; __u32 DR4; __u32 num_cliprects; /** This is a struct drm_clip_rect *cliprects */ __u64 cliprects_ptr; }; struct drm_i915_gem_exec_object2 { /** * User's handle for a buffer to be bound into the GTT for this * operation. */ __u32 handle; /** Number of relocations to be performed on this buffer */ __u32 relocation_count; /** * Pointer to array of struct drm_i915_gem_relocation_entry containing * the relocations to be performed in this buffer. */ __u64 relocs_ptr; /** Required alignment in graphics aperture */ __u64 alignment; /** * When the EXEC_OBJECT_PINNED flag is specified this is populated by * the user with the GTT offset at which this object will be pinned. * When the I915_EXEC_NO_RELOC flag is specified this must contain the * presumed_offset of the object. * During execbuffer2 the kernel populates it with the value of the * current GTT offset of the object, for future presumed_offset writes. */ __u64 offset; #define EXEC_OBJECT_NEEDS_FENCE (1<<0) #define EXEC_OBJECT_NEEDS_GTT (1<<1) #define EXEC_OBJECT_WRITE (1<<2) #define EXEC_OBJECT_SUPPORTS_48B_ADDRESS (1<<3) #define EXEC_OBJECT_PINNED (1<<4) #define EXEC_OBJECT_PAD_TO_SIZE (1<<5) /* The kernel implicitly tracks GPU activity on all GEM objects, and * synchronises operations with outstanding rendering. This includes * rendering on other devices if exported via dma-buf. However, sometimes * this tracking is too coarse and the user knows better. For example, * if the object is split into non-overlapping ranges shared between different * clients or engines (i.e. suballocating objects), the implicit tracking * by kernel assumes that each operation affects the whole object rather * than an individual range, causing needless synchronisation between clients. * The kernel will also forgo any CPU cache flushes prior to rendering from * the object as the client is expected to be also handling such domain * tracking. * * The kernel maintains the implicit tracking in order to manage resources * used by the GPU - this flag only disables the synchronisation prior to * rendering with this object in this execbuf. * * Opting out of implicit synhronisation requires the user to do its own * explicit tracking to avoid rendering corruption. See, for example, * I915_PARAM_HAS_EXEC_FENCE to order execbufs and execute them asynchronously. */ #define EXEC_OBJECT_ASYNC (1<<6) /* Request that the contents of this execobject be copied into the error * state upon a GPU hang involving this batch for post-mortem debugging. * These buffers are recorded in no particular order as "user" in * /sys/class/drm/cardN/error. Query I915_PARAM_HAS_EXEC_CAPTURE to see * if the kernel supports this flag. */ #define EXEC_OBJECT_CAPTURE (1<<7) /* All remaining bits are MBZ and RESERVED FOR FUTURE USE */ #define __EXEC_OBJECT_UNKNOWN_FLAGS -(EXEC_OBJECT_CAPTURE<<1) __u64 flags; union { __u64 rsvd1; __u64 pad_to_size; }; __u64 rsvd2; }; struct drm_i915_gem_exec_fence { /** * User's handle for a drm_syncobj to wait on or signal. */ __u32 handle; #define I915_EXEC_FENCE_WAIT (1<<0) #define I915_EXEC_FENCE_SIGNAL (1<<1) #define __I915_EXEC_FENCE_UNKNOWN_FLAGS (-(I915_EXEC_FENCE_SIGNAL << 1)) __u32 flags; }; struct drm_i915_gem_execbuffer2 { /** * List of gem_exec_object2 structs */ __u64 buffers_ptr; __u32 buffer_count; /** Offset in the batchbuffer to start execution from. */ __u32 batch_start_offset; /** Bytes used in batchbuffer from batch_start_offset */ __u32 batch_len; __u32 DR1; __u32 DR4; __u32 num_cliprects; /** * This is a struct drm_clip_rect *cliprects if I915_EXEC_FENCE_ARRAY * is not set. If I915_EXEC_FENCE_ARRAY is set, then this is a * struct drm_i915_gem_exec_fence *fences. */ __u64 cliprects_ptr; #define I915_EXEC_RING_MASK (0x3f) #define I915_EXEC_DEFAULT (0<<0) #define I915_EXEC_RENDER (1<<0) #define I915_EXEC_BSD (2<<0) #define I915_EXEC_BLT (3<<0) #define I915_EXEC_VEBOX (4<<0) /* Used for switching the constants addressing mode on gen4+ RENDER ring. * Gen6+ only supports relative addressing to dynamic state (default) and * absolute addressing. * * These flags are ignored for the BSD and BLT rings. */ #define I915_EXEC_CONSTANTS_MASK (3<<6) #define I915_EXEC_CONSTANTS_REL_GENERAL (0<<6) /* default */ #define I915_EXEC_CONSTANTS_ABSOLUTE (1<<6) #define I915_EXEC_CONSTANTS_REL_SURFACE (2<<6) /* gen4/5 only */ __u64 flags; __u64 rsvd1; /* now used for context info */ __u64 rsvd2; }; /** Resets the SO write offset registers for transform feedback on gen7. */ #define I915_EXEC_GEN7_SOL_RESET (1<<8) /** Request a privileged ("secure") batch buffer. Note only available for * DRM_ROOT_ONLY | DRM_MASTER processes. */ #define I915_EXEC_SECURE (1<<9) /** Inform the kernel that the batch is and will always be pinned. This * negates the requirement for a workaround to be performed to avoid * an incoherent CS (such as can be found on 830/845). If this flag is * not passed, the kernel will endeavour to make sure the batch is * coherent with the CS before execution. If this flag is passed, * userspace assumes the responsibility for ensuring the same. */ #define I915_EXEC_IS_PINNED (1<<10) /** Provide a hint to the kernel that the command stream and auxiliary * state buffers already holds the correct presumed addresses and so the * relocation process may be skipped if no buffers need to be moved in * preparation for the execbuffer. */ #define I915_EXEC_NO_RELOC (1<<11) /** Use the reloc.handle as an index into the exec object array rather * than as the per-file handle. */ #define I915_EXEC_HANDLE_LUT (1<<12) /** Used for switching BSD rings on the platforms with two BSD rings */ #define I915_EXEC_BSD_SHIFT (13) #define I915_EXEC_BSD_MASK (3 << I915_EXEC_BSD_SHIFT) /* default ping-pong mode */ #define I915_EXEC_BSD_DEFAULT (0 << I915_EXEC_BSD_SHIFT) #define I915_EXEC_BSD_RING1 (1 << I915_EXEC_BSD_SHIFT) #define I915_EXEC_BSD_RING2 (2 << I915_EXEC_BSD_SHIFT) /** Tell the kernel that the batchbuffer is processed by * the resource streamer. */ #define I915_EXEC_RESOURCE_STREAMER (1<<15) /* Setting I915_EXEC_FENCE_IN implies that lower_32_bits(rsvd2) represent * a sync_file fd to wait upon (in a nonblocking manner) prior to executing * the batch. * * Returns -EINVAL if the sync_file fd cannot be found. */ #define I915_EXEC_FENCE_IN (1<<16) /* Setting I915_EXEC_FENCE_OUT causes the ioctl to return a sync_file fd * in the upper_32_bits(rsvd2) upon success. Ownership of the fd is given * to the caller, and it should be close() after use. (The fd is a regular * file descriptor and will be cleaned up on process termination. It holds * a reference to the request, but nothing else.) * * The sync_file fd can be combined with other sync_file and passed either * to execbuf using I915_EXEC_FENCE_IN, to atomic KMS ioctls (so that a flip * will only occur after this request completes), or to other devices. * * Using I915_EXEC_FENCE_OUT requires use of * DRM_IOCTL_I915_GEM_EXECBUFFER2_WR ioctl so that the result is written * back to userspace. Failure to do so will cause the out-fence to always * be reported as zero, and the real fence fd to be leaked. */ #define I915_EXEC_FENCE_OUT (1<<17) /* * Traditionally the execbuf ioctl has only considered the final element in * the execobject[] to be the executable batch. Often though, the client * will known the batch object prior to construction and being able to place * it into the execobject[] array first can simplify the relocation tracking. * Setting I915_EXEC_BATCH_FIRST tells execbuf to use element 0 of the * execobject[] as the * batch instead (the default is to use the last * element). */ #define I915_EXEC_BATCH_FIRST (1<<18) /* Setting I915_FENCE_ARRAY implies that num_cliprects and cliprects_ptr * define an array of i915_gem_exec_fence structures which specify a set of * dma fences to wait upon or signal. */ #define I915_EXEC_FENCE_ARRAY (1<<19) /* * Setting I915_EXEC_FENCE_SUBMIT implies that lower_32_bits(rsvd2) represent * a sync_file fd to wait upon (in a nonblocking manner) prior to executing * the batch. * * Returns -EINVAL if the sync_file fd cannot be found. */ #define I915_EXEC_FENCE_SUBMIT (1 << 20) #define __I915_EXEC_UNKNOWN_FLAGS (-(I915_EXEC_FENCE_SUBMIT << 1)) #define I915_EXEC_CONTEXT_ID_MASK (0xffffffff) #define i915_execbuffer2_set_context_id(eb2, context) \ (eb2).rsvd1 = context & I915_EXEC_CONTEXT_ID_MASK #define i915_execbuffer2_get_context_id(eb2) \ ((eb2).rsvd1 & I915_EXEC_CONTEXT_ID_MASK) struct drm_i915_gem_pin { /** Handle of the buffer to be pinned. */ __u32 handle; __u32 pad; /** alignment required within the aperture */ __u64 alignment; /** Returned GTT offset of the buffer. */ __u64 offset; }; struct drm_i915_gem_unpin { /** Handle of the buffer to be unpinned. */ __u32 handle; __u32 pad; }; struct drm_i915_gem_busy { /** Handle of the buffer to check for busy */ __u32 handle; /** Return busy status * * A return of 0 implies that the object is idle (after * having flushed any pending activity), and a non-zero return that * the object is still in-flight on the GPU. (The GPU has not yet * signaled completion for all pending requests that reference the * object.) An object is guaranteed to become idle eventually (so * long as no new GPU commands are executed upon it). Due to the * asynchronous nature of the hardware, an object reported * as busy may become idle before the ioctl is completed. * * Furthermore, if the object is busy, which engine is busy is only * provided as a guide and only indirectly by reporting its class * (there may be more than one engine in each class). There are race * conditions which prevent the report of which engines are busy from * being always accurate. However, the converse is not true. If the * object is idle, the result of the ioctl, that all engines are idle, * is accurate. * * The returned dword is split into two fields to indicate both * the engine classess on which the object is being read, and the * engine class on which it is currently being written (if any). * * The low word (bits 0:15) indicate if the object is being written * to by any engine (there can only be one, as the GEM implicit * synchronisation rules force writes to be serialised). Only the * engine class (offset by 1, I915_ENGINE_CLASS_RENDER is reported as * 1 not 0 etc) for the last write is reported. * * The high word (bits 16:31) are a bitmask of which engines classes * are currently reading from the object. Multiple engines may be * reading from the object simultaneously. * * The value of each engine class is the same as specified in the * I915_CONTEXT_SET_ENGINES parameter and via perf, i.e. * I915_ENGINE_CLASS_RENDER, I915_ENGINE_CLASS_COPY, etc. * reported as active itself. Some hardware may have parallel * execution engines, e.g. multiple media engines, which are * mapped to the same class identifier and so are not separately * reported for busyness. * * Caveat emptor: * Only the boolean result of this query is reliable; that is whether * the object is idle or busy. The report of which engines are busy * should be only used as a heuristic. */ __u32 busy; }; /** * I915_CACHING_NONE * * GPU access is not coherent with cpu caches. Default for machines without an * LLC. */ #define I915_CACHING_NONE 0 /** * I915_CACHING_CACHED * * GPU access is coherent with cpu caches and furthermore the data is cached in * last-level caches shared between cpu cores and the gpu GT. Default on * machines with HAS_LLC. */ #define I915_CACHING_CACHED 1 /** * I915_CACHING_DISPLAY * * Special GPU caching mode which is coherent with the scanout engines. * Transparently falls back to I915_CACHING_NONE on platforms where no special * cache mode (like write-through or gfdt flushing) is available. The kernel * automatically sets this mode when using a buffer as a scanout target. * Userspace can manually set this mode to avoid a costly stall and clflush in * the hotpath of drawing the first frame. */ #define I915_CACHING_DISPLAY 2 struct drm_i915_gem_caching { /** * Handle of the buffer to set/get the caching level of. */ __u32 handle; /** * Cacheing level to apply or return value * * bits0-15 are for generic caching control (i.e. the above defined * values). bits16-31 are reserved for platform-specific variations * (e.g. l3$ caching on gen7). */ __u32 caching; }; #define I915_TILING_NONE 0 #define I915_TILING_X 1 #define I915_TILING_Y 2 #define I915_TILING_LAST I915_TILING_Y #define I915_BIT_6_SWIZZLE_NONE 0 #define I915_BIT_6_SWIZZLE_9 1 #define I915_BIT_6_SWIZZLE_9_10 2 #define I915_BIT_6_SWIZZLE_9_11 3 #define I915_BIT_6_SWIZZLE_9_10_11 4 /* Not seen by userland */ #define I915_BIT_6_SWIZZLE_UNKNOWN 5 /* Seen by userland. */ #define I915_BIT_6_SWIZZLE_9_17 6 #define I915_BIT_6_SWIZZLE_9_10_17 7 struct drm_i915_gem_set_tiling { /** Handle of the buffer to have its tiling state updated */ __u32 handle; /** * Tiling mode for the object (I915_TILING_NONE, I915_TILING_X, * I915_TILING_Y). * * This value is to be set on request, and will be updated by the * kernel on successful return with the actual chosen tiling layout. * * The tiling mode may be demoted to I915_TILING_NONE when the system * has bit 6 swizzling that can't be managed correctly by GEM. * * Buffer contents become undefined when changing tiling_mode. */ __u32 tiling_mode; /** * Stride in bytes for the object when in I915_TILING_X or * I915_TILING_Y. */ __u32 stride; /** * Returned address bit 6 swizzling required for CPU access through * mmap mapping. */ __u32 swizzle_mode; }; struct drm_i915_gem_get_tiling { /** Handle of the buffer to get tiling state for. */ __u32 handle; /** * Current tiling mode for the object (I915_TILING_NONE, I915_TILING_X, * I915_TILING_Y). */ __u32 tiling_mode; /** * Returned address bit 6 swizzling required for CPU access through * mmap mapping. */ __u32 swizzle_mode; /** * Returned address bit 6 swizzling required for CPU access through * mmap mapping whilst bound. */ __u32 phys_swizzle_mode; }; struct drm_i915_gem_get_aperture { /** Total size of the aperture used by i915_gem_execbuffer, in bytes */ __u64 aper_size; /** * Available space in the aperture used by i915_gem_execbuffer, in * bytes */ __u64 aper_available_size; }; struct drm_i915_get_pipe_from_crtc_id { /** ID of CRTC being requested **/ __u32 crtc_id; /** pipe of requested CRTC **/ __u32 pipe; }; #define I915_MADV_WILLNEED 0 #define I915_MADV_DONTNEED 1 #define __I915_MADV_PURGED 2 /* internal state */ struct drm_i915_gem_madvise { /** Handle of the buffer to change the backing store advice */ __u32 handle; /* Advice: either the buffer will be needed again in the near future, * or wont be and could be discarded under memory pressure. */ __u32 madv; /** Whether the backing store still exists. */ __u32 retained; }; /* flags */ #define I915_OVERLAY_TYPE_MASK 0xff #define I915_OVERLAY_YUV_PLANAR 0x01 #define I915_OVERLAY_YUV_PACKED 0x02 #define I915_OVERLAY_RGB 0x03 #define I915_OVERLAY_DEPTH_MASK 0xff00 #define I915_OVERLAY_RGB24 0x1000 #define I915_OVERLAY_RGB16 0x2000 #define I915_OVERLAY_RGB15 0x3000 #define I915_OVERLAY_YUV422 0x0100 #define I915_OVERLAY_YUV411 0x0200 #define I915_OVERLAY_YUV420 0x0300 #define I915_OVERLAY_YUV410 0x0400 #define I915_OVERLAY_SWAP_MASK 0xff0000 #define I915_OVERLAY_NO_SWAP 0x000000 #define I915_OVERLAY_UV_SWAP 0x010000 #define I915_OVERLAY_Y_SWAP 0x020000 #define I915_OVERLAY_Y_AND_UV_SWAP 0x030000 #define I915_OVERLAY_FLAGS_MASK 0xff000000 #define I915_OVERLAY_ENABLE 0x01000000 struct drm_intel_overlay_put_image { /* various flags and src format description */ __u32 flags; /* source picture description */ __u32 bo_handle; /* stride values and offsets are in bytes, buffer relative */ __u16 stride_Y; /* stride for packed formats */ __u16 stride_UV; __u32 offset_Y; /* offset for packet formats */ __u32 offset_U; __u32 offset_V; /* in pixels */ __u16 src_width; __u16 src_height; /* to compensate the scaling factors for partially covered surfaces */ __u16 src_scan_width; __u16 src_scan_height; /* output crtc description */ __u32 crtc_id; __u16 dst_x; __u16 dst_y; __u16 dst_width; __u16 dst_height; }; /* flags */ #define I915_OVERLAY_UPDATE_ATTRS (1<<0) #define I915_OVERLAY_UPDATE_GAMMA (1<<1) #define I915_OVERLAY_DISABLE_DEST_COLORKEY (1<<2) struct drm_intel_overlay_attrs { __u32 flags; __u32 color_key; __s32 brightness; __u32 contrast; __u32 saturation; __u32 gamma0; __u32 gamma1; __u32 gamma2; __u32 gamma3; __u32 gamma4; __u32 gamma5; }; /* * Intel sprite handling * * Color keying works with a min/mask/max tuple. Both source and destination * color keying is allowed. * * Source keying: * Sprite pixels within the min & max values, masked against the color channels * specified in the mask field, will be transparent. All other pixels will * be displayed on top of the primary plane. For RGB surfaces, only the min * and mask fields will be used; ranged compares are not allowed. * * Destination keying: * Primary plane pixels that match the min value, masked against the color * channels specified in the mask field, will be replaced by corresponding * pixels from the sprite plane. * * Note that source & destination keying are exclusive; only one can be * active on a given plane. */ #define I915_SET_COLORKEY_NONE (1<<0) /* Deprecated. Instead set * flags==0 to disable colorkeying. */ #define I915_SET_COLORKEY_DESTINATION (1<<1) #define I915_SET_COLORKEY_SOURCE (1<<2) struct drm_intel_sprite_colorkey { __u32 plane_id; __u32 min_value; __u32 channel_mask; __u32 max_value; __u32 flags; }; struct drm_i915_gem_wait { /** Handle of BO we shall wait on */ __u32 bo_handle; __u32 flags; /** Number of nanoseconds to wait, Returns time remaining. */ __s64 timeout_ns; }; struct drm_i915_gem_context_create { __u32 ctx_id; /* output: id of new context*/ __u32 pad; }; struct drm_i915_gem_context_create_ext { __u32 ctx_id; /* output: id of new context*/ __u32 flags; #define I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS (1u << 0) #define I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE (1u << 1) #define I915_CONTEXT_CREATE_FLAGS_UNKNOWN \ (-(I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE << 1)) __u64 extensions; }; struct drm_i915_gem_context_param { __u32 ctx_id; __u32 size; __u64 param; #define I915_CONTEXT_PARAM_BAN_PERIOD 0x1 #define I915_CONTEXT_PARAM_NO_ZEROMAP 0x2 #define I915_CONTEXT_PARAM_GTT_SIZE 0x3 #define I915_CONTEXT_PARAM_NO_ERROR_CAPTURE 0x4 #define I915_CONTEXT_PARAM_BANNABLE 0x5 #define I915_CONTEXT_PARAM_PRIORITY 0x6 #define I915_CONTEXT_MAX_USER_PRIORITY 1023 /* inclusive */ #define I915_CONTEXT_DEFAULT_PRIORITY 0 #define I915_CONTEXT_MIN_USER_PRIORITY -1023 /* inclusive */ /* * When using the following param, value should be a pointer to * drm_i915_gem_context_param_sseu. */ #define I915_CONTEXT_PARAM_SSEU 0x7 /* * Not all clients may want to attempt automatic recover of a context after * a hang (for example, some clients may only submit very small incremental * batches relying on known logical state of previous batches which will never * recover correctly and each attempt will hang), and so would prefer that * the context is forever banned instead. * * If set to false (0), after a reset, subsequent (and in flight) rendering * from this context is discarded, and the client will need to create a new * context to use instead. * * If set to true (1), the kernel will automatically attempt to recover the * context by skipping the hanging batch and executing the next batch starting * from the default context state (discarding the incomplete logical context * state lost due to the reset). * * On creation, all new contexts are marked as recoverable. */ #define I915_CONTEXT_PARAM_RECOVERABLE 0x8 /* * The id of the associated virtual memory address space (ppGTT) of * this context. Can be retrieved and passed to another context * (on the same fd) for both to use the same ppGTT and so share * address layouts, and avoid reloading the page tables on context * switches between themselves. * * See DRM_I915_GEM_VM_CREATE and DRM_I915_GEM_VM_DESTROY. */ #define I915_CONTEXT_PARAM_VM 0x9 /* * I915_CONTEXT_PARAM_ENGINES: * * Bind this context to operate on this subset of available engines. Henceforth, * the I915_EXEC_RING selector for DRM_IOCTL_I915_GEM_EXECBUFFER2 operates as * an index into this array of engines; I915_EXEC_DEFAULT selecting engine[0] * and upwards. Slots 0...N are filled in using the specified (class, instance). * Use * engine_class: I915_ENGINE_CLASS_INVALID, * engine_instance: I915_ENGINE_CLASS_INVALID_NONE * to specify a gap in the array that can be filled in later, e.g. by a * virtual engine used for load balancing. * * Setting the number of engines bound to the context to 0, by passing a zero * sized argument, will revert back to default settings. * * See struct i915_context_param_engines. * * Extensions: * i915_context_engines_load_balance (I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE) * i915_context_engines_bond (I915_CONTEXT_ENGINES_EXT_BOND) */ #define I915_CONTEXT_PARAM_ENGINES 0xa /* Must be kept compact -- no holes and well documented */ __u64 value; }; /** * Context SSEU programming * * It may be necessary for either functional or performance reason to configure * a context to run with a reduced number of SSEU (where SSEU stands for Slice/ * Sub-slice/EU). * * This is done by configuring SSEU configuration using the below * @struct drm_i915_gem_context_param_sseu for every supported engine which * userspace intends to use. * * Not all GPUs or engines support this functionality in which case an error * code -ENODEV will be returned. * * Also, flexibility of possible SSEU configuration permutations varies between * GPU generations and software imposed limitations. Requesting such a * combination will return an error code of -EINVAL. * * NOTE: When perf/OA is active the context's SSEU configuration is ignored in * favour of a single global setting. */ struct drm_i915_gem_context_param_sseu { /* * Engine class & instance to be configured or queried. */ struct i915_engine_class_instance engine; /* * Unknown flags must be cleared to zero. */ __u32 flags; #define I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX (1u << 0) /* * Mask of slices to enable for the context. Valid values are a subset * of the bitmask value returned for I915_PARAM_SLICE_MASK. */ __u64 slice_mask; /* * Mask of subslices to enable for the context. Valid values are a * subset of the bitmask value return by I915_PARAM_SUBSLICE_MASK. */ __u64 subslice_mask; /* * Minimum/Maximum number of EUs to enable per subslice for the * context. min_eus_per_subslice must be inferior or equal to * max_eus_per_subslice. */ __u16 min_eus_per_subslice; __u16 max_eus_per_subslice; /* * Unused for now. Must be cleared to zero. */ __u32 rsvd; }; /* * i915_context_engines_load_balance: * * Enable load balancing across this set of engines. * * Into the I915_EXEC_DEFAULT slot [0], a virtual engine is created that when * used will proxy the execbuffer request onto one of the set of engines * in such a way as to distribute the load evenly across the set. * * The set of engines must be compatible (e.g. the same HW class) as they * will share the same logical GPU context and ring. * * To intermix rendering with the virtual engine and direct rendering onto * the backing engines (bypassing the load balancing proxy), the context must * be defined to use a single timeline for all engines. */ struct i915_context_engines_load_balance { struct i915_user_extension base; __u16 engine_index; __u16 num_siblings; __u32 flags; /* all undefined flags must be zero */ __u64 mbz64; /* reserved for future use; must be zero */ struct i915_engine_class_instance engines[0]; } __attribute__((packed)); #define I915_DEFINE_CONTEXT_ENGINES_LOAD_BALANCE(name__, N__) struct { \ struct i915_user_extension base; \ __u16 engine_index; \ __u16 num_siblings; \ __u32 flags; \ __u64 mbz64; \ struct i915_engine_class_instance engines[N__]; \ } __attribute__((packed)) name__ /* * i915_context_engines_bond: * * Constructed bonded pairs for execution within a virtual engine. * * All engines are equal, but some are more equal than others. Given * the distribution of resources in the HW, it may be preferable to run * a request on a given subset of engines in parallel to a request on a * specific engine. We enable this selection of engines within a virtual * engine by specifying bonding pairs, for any given master engine we will * only execute on one of the corresponding siblings within the virtual engine. * * To execute a request in parallel on the master engine and a sibling requires * coordination with a I915_EXEC_FENCE_SUBMIT. */ struct i915_context_engines_bond { struct i915_user_extension base; struct i915_engine_class_instance master; __u16 virtual_index; /* index of virtual engine in ctx->engines[] */ __u16 num_bonds; __u64 flags; /* all undefined flags must be zero */ __u64 mbz64[4]; /* reserved for future use; must be zero */ struct i915_engine_class_instance engines[0]; } __attribute__((packed)); #define I915_DEFINE_CONTEXT_ENGINES_BOND(name__, N__) struct { \ struct i915_user_extension base; \ struct i915_engine_class_instance master; \ __u16 virtual_index; \ __u16 num_bonds; \ __u64 flags; \ __u64 mbz64[4]; \ struct i915_engine_class_instance engines[N__]; \ } __attribute__((packed)) name__ struct i915_context_param_engines { __u64 extensions; /* linked chain of extension blocks, 0 terminates */ #define I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE 0 /* see i915_context_engines_load_balance */ #define I915_CONTEXT_ENGINES_EXT_BOND 1 /* see i915_context_engines_bond */ struct i915_engine_class_instance engines[0]; } __attribute__((packed)); #define I915_DEFINE_CONTEXT_PARAM_ENGINES(name__, N__) struct { \ __u64 extensions; \ struct i915_engine_class_instance engines[N__]; \ } __attribute__((packed)) name__ struct drm_i915_gem_context_create_ext_setparam { #define I915_CONTEXT_CREATE_EXT_SETPARAM 0 struct i915_user_extension base; struct drm_i915_gem_context_param param; }; struct drm_i915_gem_context_create_ext_clone { #define I915_CONTEXT_CREATE_EXT_CLONE 1 struct i915_user_extension base; __u32 clone_id; __u32 flags; #define I915_CONTEXT_CLONE_ENGINES (1u << 0) #define I915_CONTEXT_CLONE_FLAGS (1u << 1) #define I915_CONTEXT_CLONE_SCHEDATTR (1u << 2) #define I915_CONTEXT_CLONE_SSEU (1u << 3) #define I915_CONTEXT_CLONE_TIMELINE (1u << 4) #define I915_CONTEXT_CLONE_VM (1u << 5) #define I915_CONTEXT_CLONE_UNKNOWN -(I915_CONTEXT_CLONE_VM << 1) __u64 rsvd; }; struct drm_i915_gem_context_destroy { __u32 ctx_id; __u32 pad; }; /* * DRM_I915_GEM_VM_CREATE - * * Create a new virtual memory address space (ppGTT) for use within a context * on the same file. Extensions can be provided to configure exactly how the * address space is setup upon creation. * * The id of new VM (bound to the fd) for use with I915_CONTEXT_PARAM_VM is * returned in the outparam @id. * * No flags are defined, with all bits reserved and must be zero. * * An extension chain maybe provided, starting with @extensions, and terminated * by the @next_extension being 0. Currently, no extensions are defined. * * DRM_I915_GEM_VM_DESTROY - * * Destroys a previously created VM id, specified in @id. * * No extensions or flags are allowed currently, and so must be zero. */ struct drm_i915_gem_vm_control { __u64 extensions; __u32 flags; __u32 vm_id; }; struct drm_i915_reg_read { /* * Register offset. * For 64bit wide registers where the upper 32bits don't immediately * follow the lower 32bits, the offset of the lower 32bits must * be specified */ __u64 offset; #define I915_REG_READ_8B_WA (1ul << 0) __u64 val; /* Return value */ }; /* Known registers: * * Render engine timestamp - 0x2358 + 64bit - gen7+ * - Note this register returns an invalid value if using the default * single instruction 8byte read, in order to workaround that pass * flag I915_REG_READ_8B_WA in offset field. * */ struct drm_i915_reset_stats { __u32 ctx_id; __u32 flags; /* All resets since boot/module reload, for all contexts */ __u32 reset_count; /* Number of batches lost when active in GPU, for this context */ __u32 batch_active; /* Number of batches lost pending for execution, for this context */ __u32 batch_pending; __u32 pad; }; struct drm_i915_gem_userptr { __u64 user_ptr; __u64 user_size; __u32 flags; #define I915_USERPTR_READ_ONLY 0x1 #define I915_USERPTR_UNSYNCHRONIZED 0x80000000 /** * Returned handle for the object. * * Object handles are nonzero. */ __u32 handle; }; enum drm_i915_oa_format { I915_OA_FORMAT_A13 = 1, /* HSW only */ I915_OA_FORMAT_A29, /* HSW only */ I915_OA_FORMAT_A13_B8_C8, /* HSW only */ I915_OA_FORMAT_B4_C8, /* HSW only */ I915_OA_FORMAT_A45_B8_C8, /* HSW only */ I915_OA_FORMAT_B4_C8_A16, /* HSW only */ I915_OA_FORMAT_C4_B8, /* HSW+ */ /* Gen8+ */ I915_OA_FORMAT_A12, I915_OA_FORMAT_A12_B8_C8, I915_OA_FORMAT_A32u40_A4u32_B8_C8, I915_OA_FORMAT_MAX /* non-ABI */ }; enum drm_i915_perf_property_id { /** * Open the stream for a specific context handle (as used with * execbuffer2). A stream opened for a specific context this way * won't typically require root privileges. * * This property is available in perf revision 1. */ DRM_I915_PERF_PROP_CTX_HANDLE = 1, /** * A value of 1 requests the inclusion of raw OA unit reports as * part of stream samples. * * This property is available in perf revision 1. */ DRM_I915_PERF_PROP_SAMPLE_OA, /** * The value specifies which set of OA unit metrics should be * be configured, defining the contents of any OA unit reports. * * This property is available in perf revision 1. */ DRM_I915_PERF_PROP_OA_METRICS_SET, /** * The value specifies the size and layout of OA unit reports. * * This property is available in perf revision 1. */ DRM_I915_PERF_PROP_OA_FORMAT, /** * Specifying this property implicitly requests periodic OA unit * sampling and (at least on Haswell) the sampling frequency is derived * from this exponent as follows: * * 80ns * 2^(period_exponent + 1) * * This property is available in perf revision 1. */ DRM_I915_PERF_PROP_OA_EXPONENT, /** * Specifying this property is only valid when specify a context to * filter with DRM_I915_PERF_PROP_CTX_HANDLE. Specifying this property * will hold preemption of the particular context we want to gather * performance data about. The execbuf2 submissions must include a * drm_i915_gem_execbuffer_ext_perf parameter for this to apply. * * This property is available in perf revision 3. */ DRM_I915_PERF_PROP_HOLD_PREEMPTION, /** * The value of this property set to 1 requests inclusion of GPU * timestamp in the perf sample data. */ DRM_I915_PERF_PROP_SAMPLE_GPU_TS, /** * This property requests inclusion of one of the following system * clock time in the perf sample data : * - CLOCK_REALTIME * - CLOCK_REALTIME_COARSE * - CLOCK_MONOTONIC * - CLOCK_MONOTONIC_COARSE * - CLOCK_MONOTONIC_RAW * - CLOCK_BOOTTIME */ DRM_I915_PERF_PROP_SAMPLE_SYSTEM_TS, DRM_I915_PERF_PROP_MAX /* non-ABI */ }; struct drm_i915_perf_open_param { __u32 flags; #define I915_PERF_FLAG_FD_CLOEXEC (1<<0) #define I915_PERF_FLAG_FD_NONBLOCK (1<<1) #define I915_PERF_FLAG_DISABLED (1<<2) /** The number of u64 (id, value) pairs */ __u32 num_properties; /** * Pointer to array of u64 (id, value) pairs configuring the stream * to open. */ __u64 properties_ptr; }; /** * Enable data capture for a stream that was either opened in a disabled state * via I915_PERF_FLAG_DISABLED or was later disabled via * I915_PERF_IOCTL_DISABLE. * * It is intended to be cheaper to disable and enable a stream than it may be * to close and re-open a stream with the same configuration. * * It's undefined whether any pending data for the stream will be lost. * * This ioctl is available in perf revision 1. */ #define I915_PERF_IOCTL_ENABLE _IO('i', 0x0) /** * Disable data capture for a stream. * * It is an error to try and read a stream that is disabled. * * This ioctl is available in perf revision 1. */ #define I915_PERF_IOCTL_DISABLE _IO('i', 0x1) /** * Change metrics_set captured by a stream. * * If the stream is bound to a specific context, the configuration change * will performed __inline__ with that context such that it takes effect before * the next execbuf submission. * * Returns the previously bound metrics set id, or a negative error code. * * This ioctl is available in perf revision 2. */ #define I915_PERF_IOCTL_CONFIG _IO('i', 0x2) /** * Common to all i915 perf records */ struct drm_i915_perf_record_header { __u32 type; __u16 pad; __u16 size; }; enum drm_i915_perf_record_type { /** * Samples are the work horse record type whose contents are extensible * and defined when opening an i915 perf stream based on the given * properties. * * Boolean properties following the naming convention * DRM_I915_PERF_SAMPLE_xyz_PROP request the inclusion of 'xyz' data in * every sample. * * The order of these sample properties given by userspace has no * affect on the ordering of data within a sample. The order is * documented here. * * struct { * struct drm_i915_perf_record_header header; * * { u32 oa_report[]; } && DRM_I915_PERF_PROP_SAMPLE_OA * }; */ DRM_I915_PERF_RECORD_SAMPLE = 1, /* * Indicates that one or more OA reports were not written by the * hardware. This can happen for example if an MI_REPORT_PERF_COUNT * command collides with periodic sampling - which would be more likely * at higher sampling frequencies. */ DRM_I915_PERF_RECORD_OA_REPORT_LOST = 2, /** * An error occurred that resulted in all pending OA reports being lost. */ DRM_I915_PERF_RECORD_OA_BUFFER_LOST = 3, DRM_I915_PERF_RECORD_MAX /* non-ABI */ }; /** * Structure to upload perf dynamic configuration into the kernel. */ struct drm_i915_perf_oa_config { /** String formatted like "%08x-%04x-%04x-%04x-%012x" */ char uuid[36]; __u32 n_mux_regs; __u32 n_boolean_regs; __u32 n_flex_regs; /* * These fields are pointers to tuples of u32 values (register address, * value). For example the expected length of the buffer pointed by * mux_regs_ptr is (2 * sizeof(u32) * n_mux_regs). */ __u64 mux_regs_ptr; __u64 boolean_regs_ptr; __u64 flex_regs_ptr; }; struct drm_i915_query_item { __u64 query_id; #define DRM_I915_QUERY_TOPOLOGY_INFO 1 #define DRM_I915_QUERY_ENGINE_INFO 2 #define DRM_I915_QUERY_PERF_CONFIG 3 /* Must be kept compact -- no holes and well documented */ /* * When set to zero by userspace, this is filled with the size of the * data to be written at the data_ptr pointer. The kernel sets this * value to a negative value to signal an error on a particular query * item. */ __s32 length; /* * When query_id == DRM_I915_QUERY_TOPOLOGY_INFO, must be 0. * * When query_id == DRM_I915_QUERY_PERF_CONFIG, must be one of the * following : * - DRM_I915_QUERY_PERF_CONFIG_LIST * - DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID * - DRM_I915_QUERY_PERF_CONFIG_FOR_UUID */ __u32 flags; #define DRM_I915_QUERY_PERF_CONFIG_LIST 1 #define DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID 2 #define DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_ID 3 /* * Data will be written at the location pointed by data_ptr when the * value of length matches the length of the data to be written by the * kernel. */ __u64 data_ptr; }; struct drm_i915_query { __u32 num_items; /* * Unused for now. Must be cleared to zero. */ __u32 flags; /* * This points to an array of num_items drm_i915_query_item structures. */ __u64 items_ptr; }; /* * Data written by the kernel with query DRM_I915_QUERY_TOPOLOGY_INFO : * * data: contains the 3 pieces of information : * * - the slice mask with one bit per slice telling whether a slice is * available. The availability of slice X can be queried with the following * formula : * * (data[X / 8] >> (X % 8)) & 1 * * - the subslice mask for each slice with one bit per subslice telling * whether a subslice is available. Gen12 has dual-subslices, which are * similar to two gen11 subslices. For gen12, this array represents dual- * subslices. The availability of subslice Y in slice X can be queried * with the following formula : * * (data[subslice_offset + * X * subslice_stride + * Y / 8] >> (Y % 8)) & 1 * * - the EU mask for each subslice in each slice with one bit per EU telling * whether an EU is available. The availability of EU Z in subslice Y in * slice X can be queried with the following formula : * * (data[eu_offset + * (X * max_subslices + Y) * eu_stride + * Z / 8] >> (Z % 8)) & 1 */ struct drm_i915_query_topology_info { /* * Unused for now. Must be cleared to zero. */ __u16 flags; __u16 max_slices; __u16 max_subslices; __u16 max_eus_per_subslice; /* * Offset in data[] at which the subslice masks are stored. */ __u16 subslice_offset; /* * Stride at which each of the subslice masks for each slice are * stored. */ __u16 subslice_stride; /* * Offset in data[] at which the EU masks are stored. */ __u16 eu_offset; /* * Stride at which each of the EU masks for each subslice are stored. */ __u16 eu_stride; __u8 data[]; }; /** * struct drm_i915_engine_info * * Describes one engine and it's capabilities as known to the driver. */ struct drm_i915_engine_info { /** Engine class and instance. */ struct i915_engine_class_instance engine; /** Reserved field. */ __u32 rsvd0; /** Engine flags. */ __u64 flags; /** Capabilities of this engine. */ __u64 capabilities; #define I915_VIDEO_CLASS_CAPABILITY_HEVC (1 << 0) #define I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC (1 << 1) /** Reserved fields. */ __u64 rsvd1[4]; }; /** * struct drm_i915_query_engine_info * * Engine info query enumerates all engines known to the driver by filling in * an array of struct drm_i915_engine_info structures. */ struct drm_i915_query_engine_info { /** Number of struct drm_i915_engine_info structs following. */ __u32 num_engines; /** MBZ */ __u32 rsvd[3]; /** Marker for drm_i915_engine_info structures. */ struct drm_i915_engine_info engines[]; }; /* * Data written by the kernel with query DRM_I915_QUERY_PERF_CONFIG. */ struct drm_i915_query_perf_config { union { /* * When query_item.flags == DRM_I915_QUERY_PERF_CONFIG_LIST, i915 sets * this fields to the number of configurations available. */ __u64 n_configs; /* * When query_id == DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_ID, * i915 will use the value in this field as configuration * identifier to decide what data to write into config_ptr. */ __u64 config; /* * When query_id == DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID, * i915 will use the value in this field as configuration * identifier to decide what data to write into config_ptr. * * String formatted like "%08x-%04x-%04x-%04x-%012x" */ char uuid[36]; }; /* * Unused for now. Must be cleared to zero. */ __u32 flags; /* * When query_item.flags == DRM_I915_QUERY_PERF_CONFIG_LIST, i915 will * write an array of __u64 of configuration identifiers. * * When query_item.flags == DRM_I915_QUERY_PERF_CONFIG_DATA, i915 will * write a struct drm_i915_perf_oa_config. If the following fields of * drm_i915_perf_oa_config are set not set to 0, i915 will write into * the associated pointers the values of submitted when the * configuration was created : * * - n_mux_regs * - n_boolean_regs * - n_flex_regs */ __u8 data[]; }; #if defined(__cplusplus) } #endif #endif /* _I915_DRM_H_ */ ================================================ FILE: mesa/include/drm-uapi/vc4_drm.h ================================================ /* * Copyright © 2014-2015 Broadcom * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef _VC4_DRM_H_ #define _VC4_DRM_H_ #include "drm.h" #if defined(__cplusplus) extern "C" { #endif #define DRM_VC4_SUBMIT_CL 0x00 #define DRM_VC4_WAIT_SEQNO 0x01 #define DRM_VC4_WAIT_BO 0x02 #define DRM_VC4_CREATE_BO 0x03 #define DRM_VC4_MMAP_BO 0x04 #define DRM_VC4_CREATE_SHADER_BO 0x05 #define DRM_VC4_GET_HANG_STATE 0x06 #define DRM_VC4_GET_PARAM 0x07 #define DRM_VC4_SET_TILING 0x08 #define DRM_VC4_GET_TILING 0x09 #define DRM_VC4_LABEL_BO 0x0a #define DRM_VC4_GEM_MADVISE 0x0b #define DRM_VC4_PERFMON_CREATE 0x0c #define DRM_VC4_PERFMON_DESTROY 0x0d #define DRM_VC4_PERFMON_GET_VALUES 0x0e #define DRM_IOCTL_VC4_SUBMIT_CL DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_SUBMIT_CL, struct drm_vc4_submit_cl) #define DRM_IOCTL_VC4_WAIT_SEQNO DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_WAIT_SEQNO, struct drm_vc4_wait_seqno) #define DRM_IOCTL_VC4_WAIT_BO DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_WAIT_BO, struct drm_vc4_wait_bo) #define DRM_IOCTL_VC4_CREATE_BO DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_CREATE_BO, struct drm_vc4_create_bo) #define DRM_IOCTL_VC4_MMAP_BO DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_MMAP_BO, struct drm_vc4_mmap_bo) #define DRM_IOCTL_VC4_CREATE_SHADER_BO DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_CREATE_SHADER_BO, struct drm_vc4_create_shader_bo) #define DRM_IOCTL_VC4_GET_HANG_STATE DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_GET_HANG_STATE, struct drm_vc4_get_hang_state) #define DRM_IOCTL_VC4_GET_PARAM DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_GET_PARAM, struct drm_vc4_get_param) #define DRM_IOCTL_VC4_SET_TILING DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_SET_TILING, struct drm_vc4_set_tiling) #define DRM_IOCTL_VC4_GET_TILING DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_GET_TILING, struct drm_vc4_get_tiling) #define DRM_IOCTL_VC4_LABEL_BO DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_LABEL_BO, struct drm_vc4_label_bo) #define DRM_IOCTL_VC4_GEM_MADVISE DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_GEM_MADVISE, struct drm_vc4_gem_madvise) #define DRM_IOCTL_VC4_PERFMON_CREATE DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_PERFMON_CREATE, struct drm_vc4_perfmon_create) #define DRM_IOCTL_VC4_PERFMON_DESTROY DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_PERFMON_DESTROY, struct drm_vc4_perfmon_destroy) #define DRM_IOCTL_VC4_PERFMON_GET_VALUES DRM_IOWR(DRM_COMMAND_BASE + DRM_VC4_PERFMON_GET_VALUES, struct drm_vc4_perfmon_get_values) struct drm_vc4_submit_rcl_surface { __u32 hindex; /* Handle index, or ~0 if not present. */ __u32 offset; /* Offset to start of buffer. */ /* * Bits for either render config (color_write) or load/store packet. * Bits should all be 0 for MSAA load/stores. */ __u16 bits; #define VC4_SUBMIT_RCL_SURFACE_READ_IS_FULL_RES (1 << 0) __u16 flags; }; /** * struct drm_vc4_submit_cl - ioctl argument for submitting commands to the 3D * engine. * * Drivers typically use GPU BOs to store batchbuffers / command lists and * their associated state. However, because the VC4 lacks an MMU, we have to * do validation of memory accesses by the GPU commands. If we were to store * our commands in BOs, we'd need to do uncached readback from them to do the * validation process, which is too expensive. Instead, userspace accumulates * commands and associated state in plain memory, then the kernel copies the * data to its own address space, and then validates and stores it in a GPU * BO. */ struct drm_vc4_submit_cl { /* Pointer to the binner command list. * * This is the first set of commands executed, which runs the * coordinate shader to determine where primitives land on the screen, * then writes out the state updates and draw calls necessary per tile * to the tile allocation BO. */ __u64 bin_cl; /* Pointer to the shader records. * * Shader records are the structures read by the hardware that contain * pointers to uniforms, shaders, and vertex attributes. The * reference to the shader record has enough information to determine * how many pointers are necessary (fixed number for shaders/uniforms, * and an attribute count), so those BO indices into bo_handles are * just stored as __u32s before each shader record passed in. */ __u64 shader_rec; /* Pointer to uniform data and texture handles for the textures * referenced by the shader. * * For each shader state record, there is a set of uniform data in the * order referenced by the record (FS, VS, then CS). Each set of * uniform data has a __u32 index into bo_handles per texture * sample operation, in the order the QPU_W_TMUn_S writes appear in * the program. Following the texture BO handle indices is the actual * uniform data. * * The individual uniform state blocks don't have sizes passed in, * because the kernel has to determine the sizes anyway during shader * code validation. */ __u64 uniforms; __u64 bo_handles; /* Size in bytes of the binner command list. */ __u32 bin_cl_size; /* Size in bytes of the set of shader records. */ __u32 shader_rec_size; /* Number of shader records. * * This could just be computed from the contents of shader_records and * the address bits of references to them from the bin CL, but it * keeps the kernel from having to resize some allocations it makes. */ __u32 shader_rec_count; /* Size in bytes of the uniform state. */ __u32 uniforms_size; /* Number of BO handles passed in (size is that times 4). */ __u32 bo_handle_count; /* RCL setup: */ __u16 width; __u16 height; __u8 min_x_tile; __u8 min_y_tile; __u8 max_x_tile; __u8 max_y_tile; struct drm_vc4_submit_rcl_surface color_read; struct drm_vc4_submit_rcl_surface color_write; struct drm_vc4_submit_rcl_surface zs_read; struct drm_vc4_submit_rcl_surface zs_write; struct drm_vc4_submit_rcl_surface msaa_color_write; struct drm_vc4_submit_rcl_surface msaa_zs_write; __u32 clear_color[2]; __u32 clear_z; __u8 clear_s; __u32 pad:24; #define VC4_SUBMIT_CL_USE_CLEAR_COLOR (1 << 0) /* By default, the kernel gets to choose the order that the tiles are * rendered in. If this is set, then the tiles will be rendered in a * raster order, with the right-to-left vs left-to-right and * top-to-bottom vs bottom-to-top dictated by * VC4_SUBMIT_CL_RCL_ORDER_INCREASING_*. This allows overlapping * blits to be implemented using the 3D engine. */ #define VC4_SUBMIT_CL_FIXED_RCL_ORDER (1 << 1) #define VC4_SUBMIT_CL_RCL_ORDER_INCREASING_X (1 << 2) #define VC4_SUBMIT_CL_RCL_ORDER_INCREASING_Y (1 << 3) __u32 flags; /* Returned value of the seqno of this render job (for the * wait ioctl). */ __u64 seqno; /* ID of the perfmon to attach to this job. 0 means no perfmon. */ __u32 perfmonid; /* Syncobj handle to wait on. If set, processing of this render job * will not start until the syncobj is signaled. 0 means ignore. */ __u32 in_sync; /* Syncobj handle to export fence to. If set, the fence in the syncobj * will be replaced with a fence that signals upon completion of this * render job. 0 means ignore. */ __u32 out_sync; __u32 pad2; }; /** * struct drm_vc4_wait_seqno - ioctl argument for waiting for * DRM_VC4_SUBMIT_CL completion using its returned seqno. * * timeout_ns is the timeout in nanoseconds, where "0" means "don't * block, just return the status." */ struct drm_vc4_wait_seqno { __u64 seqno; __u64 timeout_ns; }; /** * struct drm_vc4_wait_bo - ioctl argument for waiting for * completion of the last DRM_VC4_SUBMIT_CL on a BO. * * This is useful for cases where multiple processes might be * rendering to a BO and you want to wait for all rendering to be * completed. */ struct drm_vc4_wait_bo { __u32 handle; __u32 pad; __u64 timeout_ns; }; /** * struct drm_vc4_create_bo - ioctl argument for creating VC4 BOs. * * There are currently no values for the flags argument, but it may be * used in a future extension. */ struct drm_vc4_create_bo { __u32 size; __u32 flags; /** Returned GEM handle for the BO. */ __u32 handle; __u32 pad; }; /** * struct drm_vc4_mmap_bo - ioctl argument for mapping VC4 BOs. * * This doesn't actually perform an mmap. Instead, it returns the * offset you need to use in an mmap on the DRM device node. This * means that tools like valgrind end up knowing about the mapped * memory. * * There are currently no values for the flags argument, but it may be * used in a future extension. */ struct drm_vc4_mmap_bo { /** Handle for the object being mapped. */ __u32 handle; __u32 flags; /** offset into the drm node to use for subsequent mmap call. */ __u64 offset; }; /** * struct drm_vc4_create_shader_bo - ioctl argument for creating VC4 * shader BOs. * * Since allowing a shader to be overwritten while it's also being * executed from would allow privlege escalation, shaders must be * created using this ioctl, and they can't be mmapped later. */ struct drm_vc4_create_shader_bo { /* Size of the data argument. */ __u32 size; /* Flags, currently must be 0. */ __u32 flags; /* Pointer to the data. */ __u64 data; /** Returned GEM handle for the BO. */ __u32 handle; /* Pad, must be 0. */ __u32 pad; }; struct drm_vc4_get_hang_state_bo { __u32 handle; __u32 paddr; __u32 size; __u32 pad; }; /** * struct drm_vc4_hang_state - ioctl argument for collecting state * from a GPU hang for analysis. */ struct drm_vc4_get_hang_state { /** Pointer to array of struct drm_vc4_get_hang_state_bo. */ __u64 bo; /** * On input, the size of the bo array. Output is the number * of bos to be returned. */ __u32 bo_count; __u32 start_bin, start_render; __u32 ct0ca, ct0ea; __u32 ct1ca, ct1ea; __u32 ct0cs, ct1cs; __u32 ct0ra0, ct1ra0; __u32 bpca, bpcs; __u32 bpoa, bpos; __u32 vpmbase; __u32 dbge; __u32 fdbgo; __u32 fdbgb; __u32 fdbgr; __u32 fdbgs; __u32 errstat; /* Pad that we may save more registers into in the future. */ __u32 pad[16]; }; #define DRM_VC4_PARAM_V3D_IDENT0 0 #define DRM_VC4_PARAM_V3D_IDENT1 1 #define DRM_VC4_PARAM_V3D_IDENT2 2 #define DRM_VC4_PARAM_SUPPORTS_BRANCHES 3 #define DRM_VC4_PARAM_SUPPORTS_ETC1 4 #define DRM_VC4_PARAM_SUPPORTS_THREADED_FS 5 #define DRM_VC4_PARAM_SUPPORTS_FIXED_RCL_ORDER 6 #define DRM_VC4_PARAM_SUPPORTS_MADVISE 7 #define DRM_VC4_PARAM_SUPPORTS_PERFMON 8 struct drm_vc4_get_param { __u32 param; __u32 pad; __u64 value; }; struct drm_vc4_get_tiling { __u32 handle; __u32 flags; __u64 modifier; }; struct drm_vc4_set_tiling { __u32 handle; __u32 flags; __u64 modifier; }; /** * struct drm_vc4_label_bo - Attach a name to a BO for debug purposes. */ struct drm_vc4_label_bo { __u32 handle; __u32 len; __u64 name; }; /* * States prefixed with '__' are internal states and cannot be passed to the * DRM_IOCTL_VC4_GEM_MADVISE ioctl. */ #define VC4_MADV_WILLNEED 0 #define VC4_MADV_DONTNEED 1 #define __VC4_MADV_PURGED 2 #define __VC4_MADV_NOTSUPP 3 struct drm_vc4_gem_madvise { __u32 handle; __u32 madv; __u32 retained; __u32 pad; }; enum { VC4_PERFCNT_FEP_VALID_PRIMS_NO_RENDER, VC4_PERFCNT_FEP_VALID_PRIMS_RENDER, VC4_PERFCNT_FEP_CLIPPED_QUADS, VC4_PERFCNT_FEP_VALID_QUADS, VC4_PERFCNT_TLB_QUADS_NOT_PASSING_STENCIL, VC4_PERFCNT_TLB_QUADS_NOT_PASSING_Z_AND_STENCIL, VC4_PERFCNT_TLB_QUADS_PASSING_Z_AND_STENCIL, VC4_PERFCNT_TLB_QUADS_ZERO_COVERAGE, VC4_PERFCNT_TLB_QUADS_NON_ZERO_COVERAGE, VC4_PERFCNT_TLB_QUADS_WRITTEN_TO_COLOR_BUF, VC4_PERFCNT_PLB_PRIMS_OUTSIDE_VIEWPORT, VC4_PERFCNT_PLB_PRIMS_NEED_CLIPPING, VC4_PERFCNT_PSE_PRIMS_REVERSED, VC4_PERFCNT_QPU_TOTAL_IDLE_CYCLES, VC4_PERFCNT_QPU_TOTAL_CLK_CYCLES_VERTEX_COORD_SHADING, VC4_PERFCNT_QPU_TOTAL_CLK_CYCLES_FRAGMENT_SHADING, VC4_PERFCNT_QPU_TOTAL_CLK_CYCLES_EXEC_VALID_INST, VC4_PERFCNT_QPU_TOTAL_CLK_CYCLES_WAITING_TMUS, VC4_PERFCNT_QPU_TOTAL_CLK_CYCLES_WAITING_SCOREBOARD, VC4_PERFCNT_QPU_TOTAL_CLK_CYCLES_WAITING_VARYINGS, VC4_PERFCNT_QPU_TOTAL_INST_CACHE_HIT, VC4_PERFCNT_QPU_TOTAL_INST_CACHE_MISS, VC4_PERFCNT_QPU_TOTAL_UNIFORM_CACHE_HIT, VC4_PERFCNT_QPU_TOTAL_UNIFORM_CACHE_MISS, VC4_PERFCNT_TMU_TOTAL_TEXT_QUADS_PROCESSED, VC4_PERFCNT_TMU_TOTAL_TEXT_CACHE_MISS, VC4_PERFCNT_VPM_TOTAL_CLK_CYCLES_VDW_STALLED, VC4_PERFCNT_VPM_TOTAL_CLK_CYCLES_VCD_STALLED, VC4_PERFCNT_L2C_TOTAL_L2_CACHE_HIT, VC4_PERFCNT_L2C_TOTAL_L2_CACHE_MISS, VC4_PERFCNT_NUM_EVENTS, }; #define DRM_VC4_MAX_PERF_COUNTERS 16 struct drm_vc4_perfmon_create { __u32 id; __u32 ncounters; __u8 events[DRM_VC4_MAX_PERF_COUNTERS]; }; struct drm_vc4_perfmon_destroy { __u32 id; }; /* * Returns the values of the performance counters tracked by this * perfmon (as an array of ncounters u64 values). * * No implicit synchronization is performed, so the user has to * guarantee that any jobs using this perfmon have already been * completed (probably by blocking on the seqno returned by the * last exec that used the perfmon). */ struct drm_vc4_perfmon_get_values { __u32 id; __u64 values_ptr; }; #if defined(__cplusplus) } #endif #endif /* _VC4_DRM_H_ */ ================================================ FILE: mesa/include/no_extern_c.h ================================================ /************************************************************************** * * Copyright 2014 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ /* * Including system's headers inside `extern "C" { ... }` is not safe, as system * headers may have C++ code in them, and C++ code inside extern "C" * leads to syntatically incorrect code. * * This is because putting code inside extern "C" won't make __cplusplus define * go away, that is, the system header being included thinks is free to use C++ * as it sees fits. * * Including non-system headers inside extern "C" is not safe either, because * non-system headers end up including system headers, hence fall in the above * case too. * * Conclusion, includes inside extern "C" is simply not portable. * * * This header helps surface these issues. */ #ifdef __cplusplus template class _IncludeInsideExternCNotPortable; #endif ================================================ FILE: mesa/include/pci_ids/i965_pci_ids.h ================================================ CHIPSET(0x29A2, i965, "Intel(R) 965G") CHIPSET(0x2992, i965, "Intel(R) 965Q") CHIPSET(0x2982, i965, "Intel(R) 965G") CHIPSET(0x2972, i965, "Intel(R) 946GZ") CHIPSET(0x2A02, i965, "Intel(R) 965GM") CHIPSET(0x2A12, i965, "Intel(R) 965GME/GLE") CHIPSET(0x2A42, g4x, "Mobile Intel® GM45 Express Chipset") CHIPSET(0x2E02, g4x, "Intel(R) Integrated Graphics Device") CHIPSET(0x2E12, g4x, "Intel(R) Q45/Q43") CHIPSET(0x2E22, g4x, "Intel(R) G45/G43") CHIPSET(0x2E32, g4x, "Intel(R) G41") CHIPSET(0x2E42, g4x, "Intel(R) B43") CHIPSET(0x2E92, g4x, "Intel(R) B43") CHIPSET(0x0042, ilk, "Intel(R) Ironlake Desktop") CHIPSET(0x0046, ilk, "Intel(R) Ironlake Mobile") CHIPSET(0x0102, snb_gt1, "Intel(R) Sandybridge Desktop") CHIPSET(0x0112, snb_gt2, "Intel(R) Sandybridge Desktop") CHIPSET(0x0122, snb_gt2, "Intel(R) Sandybridge Desktop") CHIPSET(0x0106, snb_gt1, "Intel(R) Sandybridge Mobile") CHIPSET(0x0116, snb_gt2, "Intel(R) Sandybridge Mobile") CHIPSET(0x0126, snb_gt2, "Intel(R) Sandybridge Mobile") CHIPSET(0x010A, snb_gt1, "Intel(R) Sandybridge Server") CHIPSET(0x0152, ivb_gt1, "Intel(R) Ivybridge Desktop") CHIPSET(0x0162, ivb_gt2, "Intel(R) Ivybridge Desktop") CHIPSET(0x0156, ivb_gt1, "Intel(R) Ivybridge Mobile") CHIPSET(0x0166, ivb_gt2, "Intel(R) Ivybridge Mobile") CHIPSET(0x015a, ivb_gt1, "Intel(R) Ivybridge Server") CHIPSET(0x016a, ivb_gt2, "Intel(R) Ivybridge Server") CHIPSET(0x0402, hsw_gt1, "Intel(R) Haswell Desktop") CHIPSET(0x0412, hsw_gt2, "Intel(R) Haswell Desktop") CHIPSET(0x0422, hsw_gt3, "Intel(R) Haswell Desktop") CHIPSET(0x0406, hsw_gt1, "Intel(R) Haswell Mobile") CHIPSET(0x0416, hsw_gt2, "Intel(R) Haswell Mobile") CHIPSET(0x0426, hsw_gt3, "Intel(R) Haswell Mobile") CHIPSET(0x040A, hsw_gt1, "Intel(R) Haswell Server") CHIPSET(0x041A, hsw_gt2, "Intel(R) Haswell Server") CHIPSET(0x042A, hsw_gt3, "Intel(R) Haswell Server") CHIPSET(0x040B, hsw_gt1, "Intel(R) Haswell") CHIPSET(0x041B, hsw_gt2, "Intel(R) Haswell") CHIPSET(0x042B, hsw_gt3, "Intel(R) Haswell") CHIPSET(0x040E, hsw_gt1, "Intel(R) Haswell") CHIPSET(0x041E, hsw_gt2, "Intel(R) Haswell") CHIPSET(0x042E, hsw_gt3, "Intel(R) Haswell") CHIPSET(0x0C02, hsw_gt1, "Intel(R) Haswell Desktop") CHIPSET(0x0C12, hsw_gt2, "Intel(R) Haswell Desktop") CHIPSET(0x0C22, hsw_gt3, "Intel(R) Haswell Desktop") CHIPSET(0x0C06, hsw_gt1, "Intel(R) Haswell Mobile") CHIPSET(0x0C16, hsw_gt2, "Intel(R) Haswell Mobile") CHIPSET(0x0C26, hsw_gt3, "Intel(R) Haswell Mobile") CHIPSET(0x0C0A, hsw_gt1, "Intel(R) Haswell Server") CHIPSET(0x0C1A, hsw_gt2, "Intel(R) Haswell Server") CHIPSET(0x0C2A, hsw_gt3, "Intel(R) Haswell Server") CHIPSET(0x0C0B, hsw_gt1, "Intel(R) Haswell") CHIPSET(0x0C1B, hsw_gt2, "Intel(R) Haswell") CHIPSET(0x0C2B, hsw_gt3, "Intel(R) Haswell") CHIPSET(0x0C0E, hsw_gt1, "Intel(R) Haswell") CHIPSET(0x0C1E, hsw_gt2, "Intel(R) Haswell") CHIPSET(0x0C2E, hsw_gt3, "Intel(R) Haswell") CHIPSET(0x0A02, hsw_gt1, "Intel(R) Haswell Desktop") CHIPSET(0x0A12, hsw_gt2, "Intel(R) Haswell Desktop") CHIPSET(0x0A22, hsw_gt3, "Intel(R) Haswell Desktop") CHIPSET(0x0A06, hsw_gt1, "Intel(R) Haswell Mobile") CHIPSET(0x0A16, hsw_gt2, "Intel(R) Haswell Mobile") CHIPSET(0x0A26, hsw_gt3, "Intel(R) Haswell Mobile") CHIPSET(0x0A0A, hsw_gt1, "Intel(R) Haswell Server") CHIPSET(0x0A1A, hsw_gt2, "Intel(R) Haswell Server") CHIPSET(0x0A2A, hsw_gt3, "Intel(R) Haswell Server") CHIPSET(0x0A0B, hsw_gt1, "Intel(R) Haswell") CHIPSET(0x0A1B, hsw_gt2, "Intel(R) Haswell") CHIPSET(0x0A2B, hsw_gt3, "Intel(R) Haswell") CHIPSET(0x0A0E, hsw_gt1, "Intel(R) Haswell") CHIPSET(0x0A1E, hsw_gt2, "Intel(R) Haswell") CHIPSET(0x0A2E, hsw_gt3, "Intel(R) Haswell") CHIPSET(0x0D02, hsw_gt1, "Intel(R) Haswell Desktop") CHIPSET(0x0D12, hsw_gt2, "Intel(R) Haswell Desktop") CHIPSET(0x0D22, hsw_gt3, "Intel(R) Haswell Desktop") CHIPSET(0x0D06, hsw_gt1, "Intel(R) Haswell Mobile") CHIPSET(0x0D16, hsw_gt2, "Intel(R) Haswell Mobile") CHIPSET(0x0D26, hsw_gt3, "Intel(R) Haswell Mobile") CHIPSET(0x0D0A, hsw_gt1, "Intel(R) Haswell Server") CHIPSET(0x0D1A, hsw_gt2, "Intel(R) Haswell Server") CHIPSET(0x0D2A, hsw_gt3, "Intel(R) Haswell") CHIPSET(0x0D0B, hsw_gt1, "Intel(R) Haswell") CHIPSET(0x0D1B, hsw_gt2, "Intel(R) Haswell") CHIPSET(0x0D2B, hsw_gt3, "Intel(R) Haswell") CHIPSET(0x0D0E, hsw_gt1, "Intel(R) Haswell") CHIPSET(0x0D1E, hsw_gt2, "Intel(R) Haswell") CHIPSET(0x0D2E, hsw_gt3, "Intel(R) Haswell") CHIPSET(0x0F31, byt, "Intel(R) Bay Trail") CHIPSET(0x0F32, byt, "Intel(R) Bay Trail") CHIPSET(0x0F33, byt, "Intel(R) Bay Trail") CHIPSET(0x0157, byt, "Intel(R) Bay Trail") CHIPSET(0x0155, byt, "Intel(R) Bay Trail") CHIPSET(0x22B0, chv, "Intel(R) HD Graphics (Cherrytrail)") CHIPSET(0x22B1, chv, "Intel(R) HD Graphics XXX (Braswell)") /* Overridden in brw_get_renderer_string */ CHIPSET(0x22B2, chv, "Intel(R) HD Graphics (Cherryview)") CHIPSET(0x22B3, chv, "Intel(R) HD Graphics (Cherryview)") CHIPSET(0x1602, bdw_gt1, "Intel(R) Broadwell GT1") CHIPSET(0x1606, bdw_gt1, "Intel(R) Broadwell GT1") CHIPSET(0x160A, bdw_gt1, "Intel(R) Broadwell GT1") CHIPSET(0x160B, bdw_gt1, "Intel(R) Broadwell GT1") CHIPSET(0x160D, bdw_gt1, "Intel(R) Broadwell GT1") CHIPSET(0x160E, bdw_gt1, "Intel(R) Broadwell GT1") CHIPSET(0x1612, bdw_gt2, "Intel(R) HD Graphics 5600 (Broadwell GT2)") CHIPSET(0x1616, bdw_gt2, "Intel(R) HD Graphics 5500 (Broadwell GT2)") CHIPSET(0x161A, bdw_gt2, "Intel(R) Broadwell GT2") CHIPSET(0x161B, bdw_gt2, "Intel(R) Broadwell GT2") CHIPSET(0x161D, bdw_gt2, "Intel(R) Broadwell GT2") CHIPSET(0x161E, bdw_gt2, "Intel(R) HD Graphics 5300 (Broadwell GT2)") CHIPSET(0x1622, bdw_gt3, "Intel(R) Iris Pro 6200 (Broadwell GT3e)") CHIPSET(0x1626, bdw_gt3, "Intel(R) HD Graphics 6000 (Broadwell GT3)") CHIPSET(0x162A, bdw_gt3, "Intel(R) Iris Pro P6300 (Broadwell GT3e)") CHIPSET(0x162B, bdw_gt3, "Intel(R) Iris 6100 (Broadwell GT3)") CHIPSET(0x162D, bdw_gt3, "Intel(R) Broadwell GT3") CHIPSET(0x162E, bdw_gt3, "Intel(R) Broadwell GT3") CHIPSET(0x1902, skl_gt1, "Intel(R) HD Graphics 510 (Skylake GT1)") CHIPSET(0x1906, skl_gt1, "Intel(R) HD Graphics 510 (Skylake GT1)") CHIPSET(0x190A, skl_gt1, "Intel(R) Skylake GT1") CHIPSET(0x190B, skl_gt1, "Intel(R) HD Graphics 510 (Skylake GT1)") CHIPSET(0x190E, skl_gt1, "Intel(R) Skylake GT1") CHIPSET(0x1912, skl_gt2, "Intel(R) HD Graphics 530 (Skylake GT2)") CHIPSET(0x1913, skl_gt2, "Intel(R) Skylake GT2f") CHIPSET(0x1915, skl_gt2, "Intel(R) Skylake GT2f") CHIPSET(0x1916, skl_gt2, "Intel(R) HD Graphics 520 (Skylake GT2)") CHIPSET(0x1917, skl_gt2, "Intel(R) Skylake GT2f") CHIPSET(0x191A, skl_gt2, "Intel(R) Skylake GT2") CHIPSET(0x191B, skl_gt2, "Intel(R) HD Graphics 530 (Skylake GT2)") CHIPSET(0x191D, skl_gt2, "Intel(R) HD Graphics P530 (Skylake GT2)") CHIPSET(0x191E, skl_gt2, "Intel(R) HD Graphics 515 (Skylake GT2)") CHIPSET(0x1921, skl_gt2, "Intel(R) HD Graphics 520 (Skylake GT2)") CHIPSET(0x1923, skl_gt3, "Intel(R) Skylake GT3e") CHIPSET(0x1926, skl_gt3, "Intel(R) Iris Graphics 540 (Skylake GT3e)") CHIPSET(0x1927, skl_gt3, "Intel(R) Iris Graphics 550 (Skylake GT3e)") CHIPSET(0x192A, skl_gt4, "Intel(R) Skylake GT4") CHIPSET(0x192B, skl_gt3, "Intel(R) Iris Graphics 555 (Skylake GT3e)") CHIPSET(0x192D, skl_gt3, "Intel(R) Iris Graphics P555 (Skylake GT3e)") CHIPSET(0x1932, skl_gt4, "Intel(R) Iris Pro Graphics 580 (Skylake GT4e)") CHIPSET(0x193A, skl_gt4, "Intel(R) Iris Pro Graphics P580 (Skylake GT4e)") CHIPSET(0x193B, skl_gt4, "Intel(R) Iris Pro Graphics 580 (Skylake GT4e)") CHIPSET(0x193D, skl_gt4, "Intel(R) Iris Pro Graphics P580 (Skylake GT4e)") CHIPSET(0x0A84, bxt, "Intel(R) HD Graphics (Broxton)") CHIPSET(0x1A84, bxt, "Intel(R) HD Graphics (Broxton)") CHIPSET(0x1A85, bxt_2x6, "Intel(R) HD Graphics (Broxton 2x6)") CHIPSET(0x5A84, bxt, "Intel(R) HD Graphics 505 (Broxton)") CHIPSET(0x5A85, bxt_2x6, "Intel(R) HD Graphics 500 (Broxton 2x6)") CHIPSET(0x5902, kbl_gt1, "Intel(R) HD Graphics 610 (Kaby Lake GT1)") CHIPSET(0x5906, kbl_gt1, "Intel(R) HD Graphics 610 (Kaby Lake GT1)") CHIPSET(0x590A, kbl_gt1, "Intel(R) Kabylake GT1") CHIPSET(0x5908, kbl_gt1, "Intel(R) Kabylake GT1") CHIPSET(0x590B, kbl_gt1, "Intel(R) Kabylake GT1") CHIPSET(0x590E, kbl_gt1, "Intel(R) Kabylake GT1") CHIPSET(0x5913, kbl_gt1_5, "Intel(R) Kabylake GT1.5") CHIPSET(0x5915, kbl_gt1_5, "Intel(R) Kabylake GT1.5") CHIPSET(0x5917, kbl_gt2, "Intel(R) UHD Graphics 620 (Kabylake GT2)") CHIPSET(0x5912, kbl_gt2, "Intel(R) HD Graphics 630 (Kaby Lake GT2)") CHIPSET(0x5916, kbl_gt2, "Intel(R) HD Graphics 620 (Kaby Lake GT2)") CHIPSET(0x591A, kbl_gt2, "Intel(R) HD Graphics P630 (Kaby Lake GT2)") CHIPSET(0x591B, kbl_gt2, "Intel(R) HD Graphics 630 (Kaby Lake GT2)") CHIPSET(0x591D, kbl_gt2, "Intel(R) HD Graphics P630 (Kaby Lake GT2)") CHIPSET(0x591E, kbl_gt2, "Intel(R) HD Graphics 615 (Kaby Lake GT2)") CHIPSET(0x5921, kbl_gt2, "Intel(R) Kabylake GT2F") CHIPSET(0x5923, kbl_gt3, "Intel(R) Kabylake GT3") CHIPSET(0x5926, kbl_gt3, "Intel(R) Iris Plus Graphics 640 (Kaby Lake GT3e)") CHIPSET(0x5927, kbl_gt3, "Intel(R) Iris Plus Graphics 650 (Kaby Lake GT3e)") CHIPSET(0x593B, kbl_gt4, "Intel(R) Kabylake GT4") CHIPSET(0x591C, kbl_gt2, "Intel(R) Amber Lake (Kabylake) GT2") CHIPSET(0x87C0, kbl_gt2, "Intel(R) Amber Lake (Kabylake) GT2") CHIPSET(0x87CA, cfl_gt2, "Intel(R) Amber Lake (Coffeelake) GT2") CHIPSET(0x3184, glk, "Intel(R) UHD Graphics 605 (Geminilake)") CHIPSET(0x3185, glk_2x6, "Intel(R) UHD Graphics 600 (Geminilake 2x6)") CHIPSET(0x3E90, cfl_gt1, "Intel(R) UHD Graphics 610 (Coffeelake 2x6 GT1)") CHIPSET(0x3E93, cfl_gt1, "Intel(R) UHD Graphics 610 (Coffeelake 2x6 GT1)") CHIPSET(0x3E99, cfl_gt1, "Intel(R) HD Graphics (Coffeelake 2x6 GT1)") CHIPSET(0x3E9C, cfl_gt1, "Intel(R) HD Graphics (Coffeelake 2x6 GT1)") CHIPSET(0x3E91, cfl_gt2, "Intel(R) UHD Graphics 630 (Coffeelake 3x8 GT2)") CHIPSET(0x3E92, cfl_gt2, "Intel(R) UHD Graphics 630 (Coffeelake 3x8 GT2)") CHIPSET(0x3E96, cfl_gt2, "Intel(R) HD Graphics (Coffeelake 3x8 GT2)") CHIPSET(0x3E98, cfl_gt2, "Intel(R) UHD Graphics 630 (Coffeelake 3x8 GT2)") CHIPSET(0x3E9A, cfl_gt2, "Intel(R) HD Graphics (Coffeelake 3x8 GT2)") CHIPSET(0x3E9B, cfl_gt2, "Intel(R) UHD Graphics 630 (Coffeelake 3x8 GT2)") CHIPSET(0x3E94, cfl_gt2, "Intel(R) HD Graphics (Coffeelake 3x8 GT2)") CHIPSET(0x3EA9, cfl_gt2, "Intel(R) HD Graphics (Coffeelake 3x8 GT2)") CHIPSET(0x3EA5, cfl_gt3, "Intel(R) HD Graphics (Coffeelake 3x8 GT3)") CHIPSET(0x3EA6, cfl_gt3, "Intel(R) HD Graphics (Coffeelake 3x8 GT3)") CHIPSET(0x3EA7, cfl_gt3, "Intel(R) HD Graphics (Coffeelake 3x8 GT3)") CHIPSET(0x3EA8, cfl_gt3, "Intel(R) HD Graphics (Coffeelake 3x8 GT3)") CHIPSET(0x3EA1, cfl_gt1, "Intel(R) UHD Graphics (Whiskey Lake 2x6 GT1)") CHIPSET(0x3EA4, cfl_gt1, "Intel(R) UHD Graphics (Whiskey Lake 3x8 GT1)") CHIPSET(0x3EA0, cfl_gt2, "Intel(R) UHD Graphics (Whiskey Lake 3x8 GT2)") CHIPSET(0x3EA3, cfl_gt2, "Intel(R) UHD Graphics (Whiskey Lake 3x8 GT2)") CHIPSET(0x3EA2, cfl_gt3, "Intel(R) UHD Graphics (Whiskey Lake 3x8 GT3)") CHIPSET(0x9B21, cfl_gt1, "Intel(R) UHD Graphics (Comet Lake 2x6 GT1)") CHIPSET(0x9BA0, cfl_gt1, "Intel(R) UHD Graphics (Comet Lake 2x6 GT1)") CHIPSET(0x9BA2, cfl_gt1, "Intel(R) UHD Graphics (Comet Lake 2x6 GT1)") CHIPSET(0x9BA4, cfl_gt1, "Intel(R) UHD Graphics (Comet Lake 2x6 GT1)") CHIPSET(0x9BA5, cfl_gt1, "Intel(R) UHD Graphics (Comet Lake 2x6 GT1)") CHIPSET(0x9BA8, cfl_gt1, "Intel(R) UHD Graphics (Comet Lake 2x6 GT1)") CHIPSET(0x9BAA, cfl_gt1, "Intel(R) UHD Graphics (Comet Lake 2x6 GT1)") CHIPSET(0x9BAB, cfl_gt1, "Intel(R) UHD Graphics (Comet Lake 2x6 GT1)") CHIPSET(0x9BAC, cfl_gt1, "Intel(R) UHD Graphics (Comet Lake 2x6 GT1)") CHIPSET(0x9B41, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BC0, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BC2, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BC4, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BC5, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BC6, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BC8, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BCA, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BCB, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BCC, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BE6, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x9BF6, cfl_gt2, "Intel(R) UHD Graphics (Comet Lake 3x8 GT2)") CHIPSET(0x5A49, cnl_2x8, "Intel(R) HD Graphics (Cannonlake 2x8 GT0.5)") CHIPSET(0x5A4A, cnl_2x8, "Intel(R) HD Graphics (Cannonlake 2x8 GT0.5)") CHIPSET(0x5A41, cnl_3x8, "Intel(R) HD Graphics (Cannonlake 3x8 GT1)") CHIPSET(0x5A42, cnl_3x8, "Intel(R) HD Graphics (Cannonlake 3x8 GT1)") CHIPSET(0x5A44, cnl_3x8, "Intel(R) HD Graphics (Cannonlake 3x8 GT1)") CHIPSET(0x5A59, cnl_4x8, "Intel(R) HD Graphics (Cannonlake 4x8 GT1.5)") CHIPSET(0x5A5A, cnl_4x8, "Intel(R) HD Graphics (Cannonlake 4x8 GT1.5)") CHIPSET(0x5A5C, cnl_4x8, "Intel(R) HD Graphics (Cannonlake 4x8 GT1.5)") CHIPSET(0x5A50, cnl_5x8, "Intel(R) HD Graphics (Cannonlake 5x8 GT2)") CHIPSET(0x5A51, cnl_5x8, "Intel(R) HD Graphics (Cannonlake 5x8 GT2)") CHIPSET(0x5A52, cnl_5x8, "Intel(R) HD Graphics (Cannonlake 5x8 GT2)") CHIPSET(0x5A54, cnl_5x8, "Intel(R) HD Graphics (Cannonlake 5x8 GT2)") CHIPSET(0x8A50, icl_8x8, "Intel(R) HD Graphics (Ice Lake 8x8 GT2)") CHIPSET(0x8A51, icl_8x8, "Intel(R) Iris(R) Plus Graphics (Ice Lake 8x8 GT2)") CHIPSET(0x8A52, icl_8x8, "Intel(R) Iris(R) Plus Graphics (Ice Lake 8x8 GT2)") CHIPSET(0x8A53, icl_8x8, "Intel(R) Iris(R) Plus Graphics (Ice Lake 8x8 GT2)") CHIPSET(0x8A54, icl_6x8, "Intel(R) Iris(R) Plus Graphics (Ice Lake 6x8 GT1.5)") CHIPSET(0x8A56, icl_4x8, "Intel(R) UHD Graphics (Ice Lake 4x8 GT1)") CHIPSET(0x8A57, icl_6x8, "Intel(R) HD Graphics (Ice Lake 6x8 GT1.5)") CHIPSET(0x8A58, icl_4x8, "Intel(R) UHD Graphics (Ice Lake 4x8 GT1)") CHIPSET(0x8A59, icl_6x8, "Intel(R) HD Graphics (Ice Lake 6x8 GT1.5)") CHIPSET(0x8A5A, icl_6x8, "Intel(R) Iris(R) Plus Graphics (Ice Lake 6x8 GT1.5)") CHIPSET(0x8A5B, icl_4x8, "Intel(R) HD Graphics (Ice Lake 4x8 GT1)") CHIPSET(0x8A5C, icl_6x8, "Intel(R) Iris(R) Plus Graphics (Ice Lake 6x8 GT1.5)") CHIPSET(0x8A5D, icl_4x8, "Intel(R) HD Graphics (Ice Lake 4x8 GT1)") CHIPSET(0x8A71, icl_1x8, "Intel(R) HD Graphics (Ice Lake 1x8 GT0.5)") CHIPSET(0x4500, ehl_4x8, "Intel(R) HD Graphics (Elkhart Lake 4x8)") CHIPSET(0x4571, ehl_4x8, "Intel(R) HD Graphics (Elkhart Lake 4x8)") CHIPSET(0x4551, ehl_4x4, "Intel(R) HD Graphics (Elkhart Lake 4x4)") CHIPSET(0x4541, ehl_2x4, "Intel(R) HD Graphics (Elkhart Lake 2x4)") ================================================ FILE: mesa/include/pci_ids/iris_pci_ids.h ================================================ ================================================ FILE: mesa/meson.build ================================================ mesa_src = [ 'src/intel/dev/gen_device_info.c', 'src/util/bitscan.c', 'src/util/hash_table.c', 'src/util/ralloc.c', ] mesa_inc = include_directories('include', 'include/drm-uapi', 'src', 'src/mesa', 'src/intel', 'src/util') mesa_config = [ '-DHAVE_PTHREAD' ] if cc.has_function('timespec_get') mesa_config += [ '-DHAVE_TIMESPEC_GET' ] endif mesa_flags = mesa_config + [ '-Wno-unused-parameter', '-Wno-initializer-overrides' ] if c.has_argument('-Wno-override-init') mesa_flags += [ '-Wno-override-init' ] endif mesa = static_library('mesa', mesa_src, c_args : mesa_flags, include_directories : mesa_inc) mesa_dep = declare_dependency(compile_args: mesa_config, link_with : mesa, include_directories : mesa_inc) ================================================ FILE: mesa/src/compiler/shader_enums.h ================================================ /* * Mesa 3-D graphics library * * Copyright (C) 1999-2008 Brian Paul All Rights Reserved. * Copyright (C) 2009 VMware, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SHADER_ENUMS_H #define SHADER_ENUMS_H #include #ifdef __cplusplus extern "C" { #endif /** * Shader stages. * * The order must match how shaders are ordered in the pipeline. * The GLSL linker assumes that if i is the maximum number of * invocations in a sub-group. The maximum * supported in this extension is 64." * * The spec defines this as a uniform. However, it's highly unlikely that * implementations actually treat it as a uniform (which is loaded from a * constant buffer). Most likely, this is an implementation-wide constant, * or perhaps something that depends on the shader stage. */ SYSTEM_VALUE_SUBGROUP_SIZE, /** * From the GL_ARB_shader_ballot spec: * * "The variable holds the index of the * invocation within sub-group. This variable is in the range 0 to * -1, where is the total * number of invocations in a sub-group." */ SYSTEM_VALUE_SUBGROUP_INVOCATION, /** * From the GL_ARB_shader_ballot spec: * * "The variables provide a bitmask for all * invocations, with one bit per invocation starting with the least * significant bit, according to the following table, * * variable equation for bit values * -------------------- ------------------------------------ * gl_SubGroupEqMaskARB bit index == gl_SubGroupInvocationARB * gl_SubGroupGeMaskARB bit index >= gl_SubGroupInvocationARB * gl_SubGroupGtMaskARB bit index > gl_SubGroupInvocationARB * gl_SubGroupLeMaskARB bit index <= gl_SubGroupInvocationARB * gl_SubGroupLtMaskARB bit index < gl_SubGroupInvocationARB */ SYSTEM_VALUE_SUBGROUP_EQ_MASK, SYSTEM_VALUE_SUBGROUP_GE_MASK, SYSTEM_VALUE_SUBGROUP_GT_MASK, SYSTEM_VALUE_SUBGROUP_LE_MASK, SYSTEM_VALUE_SUBGROUP_LT_MASK, /*@}*/ /** * Builtin variables added by VK_KHR_subgroups */ /*@{*/ SYSTEM_VALUE_NUM_SUBGROUPS, SYSTEM_VALUE_SUBGROUP_ID, /*@}*/ /*@}*/ /** * \name Vertex shader system values */ /*@{*/ /** * OpenGL-style vertex ID. * * Section 2.11.7 (Shader Execution), subsection Shader Inputs, of the * OpenGL 3.3 core profile spec says: * * "gl_VertexID holds the integer index i implicitly passed by * DrawArrays or one of the other drawing commands defined in section * 2.8.3." * * Section 2.8.3 (Drawing Commands) of the same spec says: * * "The commands....are equivalent to the commands with the same base * name (without the BaseVertex suffix), except that the ith element * transferred by the corresponding draw call will be taken from * element indices[i] + basevertex of each enabled array." * * Additionally, the overview in the GL_ARB_shader_draw_parameters spec * says: * * "In unextended GL, vertex shaders have inputs named gl_VertexID and * gl_InstanceID, which contain, respectively the index of the vertex * and instance. The value of gl_VertexID is the implicitly passed * index of the vertex being processed, which includes the value of * baseVertex, for those commands that accept it." * * gl_VertexID gets basevertex added in. This differs from DirectX where * SV_VertexID does \b not get basevertex added in. * * \note * If all system values are available, \c SYSTEM_VALUE_VERTEX_ID will be * equal to \c SYSTEM_VALUE_VERTEX_ID_ZERO_BASE plus * \c SYSTEM_VALUE_BASE_VERTEX. * * \sa SYSTEM_VALUE_VERTEX_ID_ZERO_BASE, SYSTEM_VALUE_BASE_VERTEX */ SYSTEM_VALUE_VERTEX_ID, /** * Instanced ID as supplied to gl_InstanceID * * Values assigned to gl_InstanceID always begin with zero, regardless of * the value of baseinstance. * * Section 11.1.3.9 (Shader Inputs) of the OpenGL 4.4 core profile spec * says: * * "gl_InstanceID holds the integer instance number of the current * primitive in an instanced draw call (see section 10.5)." * * Through a big chain of pseudocode, section 10.5 describes that * baseinstance is not counted by gl_InstanceID. In that section, notice * * "If an enabled vertex attribute array is instanced (it has a * non-zero divisor as specified by VertexAttribDivisor), the element * index that is transferred to the GL, for all vertices, is given by * * floor(instance/divisor) + baseinstance * * If an array corresponding to an attribute required by a vertex * shader is not enabled, then the corresponding element is taken from * the current attribute state (see section 10.2)." * * Note that baseinstance is \b not included in the value of instance. */ SYSTEM_VALUE_INSTANCE_ID, /** * Vulkan InstanceIndex. * * InstanceIndex = gl_InstanceID + gl_BaseInstance */ SYSTEM_VALUE_INSTANCE_INDEX, /** * DirectX-style vertex ID. * * Unlike \c SYSTEM_VALUE_VERTEX_ID, this system value does \b not include * the value of basevertex. * * \sa SYSTEM_VALUE_VERTEX_ID, SYSTEM_VALUE_BASE_VERTEX */ SYSTEM_VALUE_VERTEX_ID_ZERO_BASE, /** * Value of \c basevertex passed to \c glDrawElementsBaseVertex and similar * functions. * * \sa SYSTEM_VALUE_VERTEX_ID, SYSTEM_VALUE_VERTEX_ID_ZERO_BASE */ SYSTEM_VALUE_BASE_VERTEX, /** * Depending on the type of the draw call (indexed or non-indexed), * is the value of \c basevertex passed to \c glDrawElementsBaseVertex and * similar, or is the value of \c first passed to \c glDrawArrays and * similar. * * \note * It can be used to calculate the \c SYSTEM_VALUE_VERTEX_ID as * \c SYSTEM_VALUE_VERTEX_ID_ZERO_BASE plus \c SYSTEM_VALUE_FIRST_VERTEX. * * \sa SYSTEM_VALUE_VERTEX_ID_ZERO_BASE, SYSTEM_VALUE_VERTEX_ID */ SYSTEM_VALUE_FIRST_VERTEX, /** * If the Draw command used to start the rendering was an indexed draw * or not (~0/0). Useful to calculate \c SYSTEM_VALUE_BASE_VERTEX as * \c SYSTEM_VALUE_IS_INDEXED_DRAW & \c SYSTEM_VALUE_FIRST_VERTEX. */ SYSTEM_VALUE_IS_INDEXED_DRAW, /** * Value of \c baseinstance passed to instanced draw entry points * * \sa SYSTEM_VALUE_INSTANCE_ID */ SYSTEM_VALUE_BASE_INSTANCE, /** * From _ARB_shader_draw_parameters: * * "Additionally, this extension adds a further built-in variable, * gl_DrawID to the shading language. This variable contains the index * of the draw currently being processed by a Multi* variant of a * drawing command (such as MultiDrawElements or * MultiDrawArraysIndirect)." * * If GL_ARB_multi_draw_indirect is not supported, this is always 0. */ SYSTEM_VALUE_DRAW_ID, /*@}*/ /** * \name Geometry shader system values */ /*@{*/ SYSTEM_VALUE_INVOCATION_ID, /**< (Also in Tessellation Control shader) */ /*@}*/ /** * \name Fragment shader system values */ /*@{*/ SYSTEM_VALUE_FRAG_COORD, SYSTEM_VALUE_FRONT_FACE, SYSTEM_VALUE_SAMPLE_ID, SYSTEM_VALUE_SAMPLE_POS, SYSTEM_VALUE_SAMPLE_MASK_IN, SYSTEM_VALUE_HELPER_INVOCATION, /*@}*/ /** * \name Tessellation Evaluation shader system values */ /*@{*/ SYSTEM_VALUE_TESS_COORD, SYSTEM_VALUE_VERTICES_IN, /**< Tessellation vertices in input patch */ SYSTEM_VALUE_PRIMITIVE_ID, SYSTEM_VALUE_TESS_LEVEL_OUTER, /**< TES input */ SYSTEM_VALUE_TESS_LEVEL_INNER, /**< TES input */ /*@}*/ /** * \name Compute shader system values */ /*@{*/ SYSTEM_VALUE_LOCAL_INVOCATION_ID, SYSTEM_VALUE_LOCAL_INVOCATION_INDEX, SYSTEM_VALUE_GLOBAL_INVOCATION_ID, SYSTEM_VALUE_GLOBAL_INVOCATION_INDEX, SYSTEM_VALUE_WORK_GROUP_ID, SYSTEM_VALUE_NUM_WORK_GROUPS, SYSTEM_VALUE_LOCAL_GROUP_SIZE, SYSTEM_VALUE_GLOBAL_GROUP_SIZE, SYSTEM_VALUE_WORK_DIM, /*@}*/ /** Required for VK_KHR_device_group */ SYSTEM_VALUE_DEVICE_INDEX, /** Required for VK_KHX_multiview */ SYSTEM_VALUE_VIEW_INDEX, /** * Driver internal vertex-count, used (for example) for drivers to * calculate stride for stream-out outputs. Not externally visible. */ SYSTEM_VALUE_VERTEX_CNT, /** * Driver internal varying-coord, used for varying-fetch instructions. * Not externally visible. */ SYSTEM_VALUE_VARYING_COORD, SYSTEM_VALUE_MAX /**< Number of values */ } gl_system_value; const char *gl_system_value_name(gl_system_value sysval); /** * The possible interpolation qualifiers that can be applied to a fragment * shader input in GLSL. * * Note: INTERP_MODE_NONE must be 0 so that memsetting the * ir_variable data structure to 0 causes the default behavior. */ enum glsl_interp_mode { INTERP_MODE_NONE = 0, INTERP_MODE_SMOOTH, INTERP_MODE_FLAT, INTERP_MODE_NOPERSPECTIVE, INTERP_MODE_COUNT /**< Number of interpolation qualifiers */ }; enum glsl_interface_packing { GLSL_INTERFACE_PACKING_STD140, GLSL_INTERFACE_PACKING_SHARED, GLSL_INTERFACE_PACKING_PACKED, GLSL_INTERFACE_PACKING_STD430 }; const char *glsl_interp_mode_name(enum glsl_interp_mode qual); /** * Fragment program results */ typedef enum { FRAG_RESULT_DEPTH = 0, FRAG_RESULT_STENCIL = 1, /* If a single color should be written to all render targets, this * register is written. No FRAG_RESULT_DATAn will be written. */ FRAG_RESULT_COLOR = 2, FRAG_RESULT_SAMPLE_MASK = 3, /* FRAG_RESULT_DATAn are the per-render-target (GLSL gl_FragData[n] * or ARB_fragment_program fragment.color[n]) color results. If * any are written, FRAG_RESULT_COLOR will not be written. * FRAG_RESULT_DATA1 and up are simply for the benefit of * gl_frag_result_name() and not to be construed as an upper bound */ FRAG_RESULT_DATA0 = 4, FRAG_RESULT_DATA1, FRAG_RESULT_DATA2, FRAG_RESULT_DATA3, FRAG_RESULT_DATA4, FRAG_RESULT_DATA5, FRAG_RESULT_DATA6, FRAG_RESULT_DATA7, } gl_frag_result; const char *gl_frag_result_name(gl_frag_result result); #define FRAG_RESULT_MAX (FRAG_RESULT_DATA0 + MAX_DRAW_BUFFERS) /** * \brief Layout qualifiers for gl_FragDepth. * * Extension AMD_conservative_depth allows gl_FragDepth to be redeclared with * a layout qualifier. * * \see enum ir_depth_layout */ enum gl_frag_depth_layout { FRAG_DEPTH_LAYOUT_NONE, /**< No layout is specified. */ FRAG_DEPTH_LAYOUT_ANY, FRAG_DEPTH_LAYOUT_GREATER, FRAG_DEPTH_LAYOUT_LESS, FRAG_DEPTH_LAYOUT_UNCHANGED }; /** * \brief Buffer access qualifiers */ enum gl_access_qualifier { ACCESS_COHERENT = (1 << 0), ACCESS_RESTRICT = (1 << 1), ACCESS_VOLATILE = (1 << 2), ACCESS_NON_READABLE = (1 << 3), ACCESS_NON_WRITEABLE = (1 << 4), /** The access may use a non-uniform buffer or image index */ ACCESS_NON_UNIFORM = (1 << 5), }; /** * \brief Blend support qualifiers */ enum gl_advanced_blend_mode { BLEND_NONE = 0x0000, BLEND_MULTIPLY = 0x0001, BLEND_SCREEN = 0x0002, BLEND_OVERLAY = 0x0004, BLEND_DARKEN = 0x0008, BLEND_LIGHTEN = 0x0010, BLEND_COLORDODGE = 0x0020, BLEND_COLORBURN = 0x0040, BLEND_HARDLIGHT = 0x0080, BLEND_SOFTLIGHT = 0x0100, BLEND_DIFFERENCE = 0x0200, BLEND_EXCLUSION = 0x0400, BLEND_HSL_HUE = 0x0800, BLEND_HSL_SATURATION = 0x1000, BLEND_HSL_COLOR = 0x2000, BLEND_HSL_LUMINOSITY = 0x4000, BLEND_ALL = 0x7fff, }; enum gl_tess_spacing { TESS_SPACING_UNSPECIFIED, TESS_SPACING_EQUAL, TESS_SPACING_FRACTIONAL_ODD, TESS_SPACING_FRACTIONAL_EVEN, }; /** * A compare function enum for use in compiler lowering passes. This is in * the same order as GL's compare functions (shifted down by GL_NEVER), and is * exactly the same as gallium's PIPE_FUNC_*. */ enum compare_func { COMPARE_FUNC_NEVER, COMPARE_FUNC_LESS, COMPARE_FUNC_EQUAL, COMPARE_FUNC_LEQUAL, COMPARE_FUNC_GREATER, COMPARE_FUNC_NOTEQUAL, COMPARE_FUNC_GEQUAL, COMPARE_FUNC_ALWAYS, }; /** * Arrangements for grouping invocations from NV_compute_shader_derivatives. * * The extension provides new layout qualifiers that support two different * arrangements of compute shader invocations for the purpose of derivative * computation. When specifying * * layout(derivative_group_quadsNV) in; * * compute shader invocations are grouped into 2x2x1 arrays whose four local * invocation ID values follow the pattern: * * +-----------------+------------------+ * | (2x+0, 2y+0, z) | (2x+1, 2y+0, z) | * +-----------------+------------------+ * | (2x+0, 2y+1, z) | (2x+1, 2y+1, z) | * +-----------------+------------------+ * * where Y increases from bottom to top. When specifying * * layout(derivative_group_linearNV) in; * * compute shader invocations are grouped into 2x2x1 arrays whose four local * invocation index values follow the pattern: * * +------+------+ * | 4n+0 | 4n+1 | * +------+------+ * | 4n+2 | 4n+3 | * +------+------+ * * If neither layout qualifier is specified, derivatives in compute shaders * return zero, which is consistent with the handling of built-in texture * functions like texture() in GLSL 4.50 compute shaders. */ enum gl_derivative_group { DERIVATIVE_GROUP_NONE = 0, DERIVATIVE_GROUP_QUADS, DERIVATIVE_GROUP_LINEAR, }; #ifdef __cplusplus } /* extern "C" */ #endif #endif /* SHADER_ENUMS_H */ ================================================ FILE: mesa/src/intel/common/gen_gem.h ================================================ /* * Copyright © 2018 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef GEN_GEM_H #define GEN_GEM_H #include #include #include #include static inline uint64_t gen_canonical_address(uint64_t v) { /* From the Broadwell PRM Vol. 2a, MI_LOAD_REGISTER_MEM::MemoryAddress: * * "This field specifies the address of the memory location where the * register value specified in the DWord above will read from. The * address specifies the DWord location of the data. Range = * GraphicsVirtualAddress[63:2] for a DWord register GraphicsAddress * [63:48] are ignored by the HW and assumed to be in correct * canonical form [63:48] == [47]." */ const int shift = 63 - 47; return (int64_t)(v << shift) >> shift; } /** * This returns a 48-bit address with the high 16 bits zeroed. * * It's the opposite of gen_canonicalize_address. */ static inline uint64_t gen_48b_address(uint64_t v) { const int shift = 63 - 47; return (uint64_t)(v << shift) >> shift; } /** * Call ioctl, restarting if it is interupted */ static inline int gen_ioctl(int fd, unsigned long request, void *arg) { int ret; do { ret = ioctl(fd, request, arg); } while (ret == -1 && (errno == EINTR || errno == EAGAIN)); return ret; } #endif /* GEN_GEM_H */ ================================================ FILE: mesa/src/intel/dev/gen_device_info.c ================================================ /* * Copyright © 2013 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include #include #include #include #include #include #include "gen_device_info.h" #include "compiler/shader_enums.h" #include "intel/common/gen_gem.h" #include "util/bitscan.h" #include "util/macros.h" #include "drm-uapi/i915_drm.h" /** * Get the PCI ID for the device name. * * Returns -1 if the device is not known. */ int gen_device_name_to_pci_device_id(const char *name) { static const struct { const char *name; int pci_id; } name_map[] = { { "brw", 0x2a02 }, { "g4x", 0x2a42 }, { "ilk", 0x0042 }, { "snb", 0x0126 }, { "ivb", 0x016a }, { "hsw", 0x0d2e }, { "byt", 0x0f33 }, { "bdw", 0x162e }, { "chv", 0x22B3 }, { "skl", 0x1912 }, { "bxt", 0x5A85 }, { "kbl", 0x5912 }, { "aml", 0x591C }, { "glk", 0x3185 }, { "cfl", 0x3E9B }, { "whl", 0x3EA1 }, { "cml", 0x9b41 }, { "cnl", 0x5a52 }, { "icl", 0x8a52 }, { "ehl", 0x4500 }, }; for (unsigned i = 0; i < ARRAY_SIZE(name_map); i++) { if (!strcmp(name_map[i].name, name)) return name_map[i].pci_id; } return -1; } /** * Get the overridden PCI ID for the device. This is set with the * INTEL_DEVID_OVERRIDE environment variable. * * Returns -1 if the override is not set. */ static int get_pci_device_id_override(void) { if (geteuid() == getuid()) { const char *devid_override = getenv("INTEL_DEVID_OVERRIDE"); if (devid_override) { const int id = gen_device_name_to_pci_device_id(devid_override); return id >= 0 ? id : strtol(devid_override, NULL, 0); } } return -1; } static const struct gen_device_info gen_device_info_i965 = { .gen = 4, .has_negative_rhw_bug = true, .num_slices = 1, .num_subslices = { 1, }, .num_eu_per_subslice = 8, .num_thread_per_eu = 4, .max_vs_threads = 16, .max_gs_threads = 2, .max_wm_threads = 8 * 4, .urb = { .size = 256, }, .timestamp_frequency = 12500000, .simulator_id = -1, }; static const struct gen_device_info gen_device_info_g4x = { .gen = 4, .has_pln = true, .has_compr4 = true, .has_surface_tile_offset = true, .is_g4x = true, .num_slices = 1, .num_subslices = { 1, }, .num_eu_per_subslice = 10, .num_thread_per_eu = 5, .max_vs_threads = 32, .max_gs_threads = 2, .max_wm_threads = 10 * 5, .urb = { .size = 384, }, .timestamp_frequency = 12500000, .simulator_id = -1, }; static const struct gen_device_info gen_device_info_ilk = { .gen = 5, .has_pln = true, .has_compr4 = true, .has_surface_tile_offset = true, .num_slices = 1, .num_subslices = { 1, }, .num_eu_per_subslice = 12, .num_thread_per_eu = 6, .max_vs_threads = 72, .max_gs_threads = 32, .max_wm_threads = 12 * 6, .urb = { .size = 1024, }, .timestamp_frequency = 12500000, .simulator_id = -1, }; static const struct gen_device_info gen_device_info_snb_gt1 = { .gen = 6, .gt = 1, .has_hiz_and_separate_stencil = true, .has_llc = true, .has_pln = true, .has_surface_tile_offset = true, .needs_unlit_centroid_workaround = true, .num_slices = 1, .num_subslices = { 1, }, .num_eu_per_subslice = 6, .num_thread_per_eu = 6, /* Not confirmed */ .max_vs_threads = 24, .max_gs_threads = 21, /* conservative; 24 if rendering disabled. */ .max_wm_threads = 40, .urb = { .size = 32, .min_entries = { [MESA_SHADER_VERTEX] = 24, }, .max_entries = { [MESA_SHADER_VERTEX] = 256, [MESA_SHADER_GEOMETRY] = 256, }, }, .timestamp_frequency = 12500000, .simulator_id = -1, }; static const struct gen_device_info gen_device_info_snb_gt2 = { .gen = 6, .gt = 2, .has_hiz_and_separate_stencil = true, .has_llc = true, .has_pln = true, .has_surface_tile_offset = true, .needs_unlit_centroid_workaround = true, .num_slices = 1, .num_subslices = { 1, }, .num_eu_per_subslice = 12, .num_thread_per_eu = 6, /* Not confirmed */ .max_vs_threads = 60, .max_gs_threads = 60, .max_wm_threads = 80, .urb = { .size = 64, .min_entries = { [MESA_SHADER_VERTEX] = 24, }, .max_entries = { [MESA_SHADER_VERTEX] = 256, [MESA_SHADER_GEOMETRY] = 256, }, }, .timestamp_frequency = 12500000, .simulator_id = -1, }; #define GEN7_FEATURES \ .gen = 7, \ .has_hiz_and_separate_stencil = true, \ .must_use_separate_stencil = true, \ .has_llc = true, \ .has_pln = true, \ .has_64bit_types = true, \ .has_surface_tile_offset = true, \ .timestamp_frequency = 12500000 static const struct gen_device_info gen_device_info_ivb_gt1 = { GEN7_FEATURES, .is_ivybridge = true, .gt = 1, .num_slices = 1, .num_subslices = { 1, }, .num_eu_per_subslice = 6, .num_thread_per_eu = 6, .l3_banks = 2, .max_vs_threads = 36, .max_tcs_threads = 36, .max_tes_threads = 36, .max_gs_threads = 36, .max_wm_threads = 48, .max_cs_threads = 36, .urb = { .size = 128, .min_entries = { [MESA_SHADER_VERTEX] = 32, [MESA_SHADER_TESS_EVAL] = 10, }, .max_entries = { [MESA_SHADER_VERTEX] = 512, [MESA_SHADER_TESS_CTRL] = 32, [MESA_SHADER_TESS_EVAL] = 288, [MESA_SHADER_GEOMETRY] = 192, }, }, .simulator_id = 7, }; static const struct gen_device_info gen_device_info_ivb_gt2 = { GEN7_FEATURES, .is_ivybridge = true, .gt = 2, .num_slices = 1, .num_subslices = { 1, }, .num_eu_per_subslice = 12, .num_thread_per_eu = 8, /* Not sure why this isn't a multiple of * @max_wm_threads ... */ .l3_banks = 4, .max_vs_threads = 128, .max_tcs_threads = 128, .max_tes_threads = 128, .max_gs_threads = 128, .max_wm_threads = 172, .max_cs_threads = 64, .urb = { .size = 256, .min_entries = { [MESA_SHADER_VERTEX] = 32, [MESA_SHADER_TESS_EVAL] = 10, }, .max_entries = { [MESA_SHADER_VERTEX] = 704, [MESA_SHADER_TESS_CTRL] = 64, [MESA_SHADER_TESS_EVAL] = 448, [MESA_SHADER_GEOMETRY] = 320, }, }, .simulator_id = 7, }; static const struct gen_device_info gen_device_info_byt = { GEN7_FEATURES, .is_baytrail = true, .gt = 1, .num_slices = 1, .num_subslices = { 1, }, .num_eu_per_subslice = 4, .num_thread_per_eu = 8, .l3_banks = 1, .has_llc = false, .max_vs_threads = 36, .max_tcs_threads = 36, .max_tes_threads = 36, .max_gs_threads = 36, .max_wm_threads = 48, .max_cs_threads = 32, .urb = { .size = 128, .min_entries = { [MESA_SHADER_VERTEX] = 32, [MESA_SHADER_TESS_EVAL] = 10, }, .max_entries = { [MESA_SHADER_VERTEX] = 512, [MESA_SHADER_TESS_CTRL] = 32, [MESA_SHADER_TESS_EVAL] = 288, [MESA_SHADER_GEOMETRY] = 192, }, }, .simulator_id = 10, }; #define HSW_FEATURES \ GEN7_FEATURES, \ .is_haswell = true, \ .supports_simd16_3src = true, \ .has_resource_streamer = true static const struct gen_device_info gen_device_info_hsw_gt1 = { HSW_FEATURES, .gt = 1, .num_slices = 1, .num_subslices = { 1, }, .num_eu_per_subslice = 10, .num_thread_per_eu = 7, .l3_banks = 2, .max_vs_threads = 70, .max_tcs_threads = 70, .max_tes_threads = 70, .max_gs_threads = 70, .max_wm_threads = 102, .max_cs_threads = 70, .urb = { .size = 128, .min_entries = { [MESA_SHADER_VERTEX] = 32, [MESA_SHADER_TESS_EVAL] = 10, }, .max_entries = { [MESA_SHADER_VERTEX] = 640, [MESA_SHADER_TESS_CTRL] = 64, [MESA_SHADER_TESS_EVAL] = 384, [MESA_SHADER_GEOMETRY] = 256, }, }, .simulator_id = 9, }; static const struct gen_device_info gen_device_info_hsw_gt2 = { HSW_FEATURES, .gt = 2, .num_slices = 1, .num_subslices = { 2, }, .num_eu_per_subslice = 10, .num_thread_per_eu = 7, .l3_banks = 4, .max_vs_threads = 280, .max_tcs_threads = 256, .max_tes_threads = 280, .max_gs_threads = 256, .max_wm_threads = 204, .max_cs_threads = 70, .urb = { .size = 256, .min_entries = { [MESA_SHADER_VERTEX] = 64, [MESA_SHADER_TESS_EVAL] = 10, }, .max_entries = { [MESA_SHADER_VERTEX] = 1664, [MESA_SHADER_TESS_CTRL] = 128, [MESA_SHADER_TESS_EVAL] = 960, [MESA_SHADER_GEOMETRY] = 640, }, }, .simulator_id = 9, }; static const struct gen_device_info gen_device_info_hsw_gt3 = { HSW_FEATURES, .gt = 3, .num_slices = 2, .num_subslices = { 2, }, .num_eu_per_subslice = 10, .num_thread_per_eu = 7, .l3_banks = 8, .max_vs_threads = 280, .max_tcs_threads = 256, .max_tes_threads = 280, .max_gs_threads = 256, .max_wm_threads = 408, .max_cs_threads = 70, .urb = { .size = 512, .min_entries = { [MESA_SHADER_VERTEX] = 64, [MESA_SHADER_TESS_EVAL] = 10, }, .max_entries = { [MESA_SHADER_VERTEX] = 1664, [MESA_SHADER_TESS_CTRL] = 128, [MESA_SHADER_TESS_EVAL] = 960, [MESA_SHADER_GEOMETRY] = 640, }, }, .simulator_id = 9, }; /* It's unclear how well supported sampling from the hiz buffer is on GEN8, * so keep things conservative for now and set has_sample_with_hiz = false. */ #define GEN8_FEATURES \ .gen = 8, \ .has_hiz_and_separate_stencil = true, \ .has_resource_streamer = true, \ .must_use_separate_stencil = true, \ .has_llc = true, \ .has_sample_with_hiz = false, \ .has_pln = true, \ .has_integer_dword_mul = true, \ .has_64bit_types = true, \ .supports_simd16_3src = true, \ .has_surface_tile_offset = true, \ .num_thread_per_eu = 7, \ .max_vs_threads = 504, \ .max_tcs_threads = 504, \ .max_tes_threads = 504, \ .max_gs_threads = 504, \ .max_wm_threads = 384, \ .timestamp_frequency = 12500000 static const struct gen_device_info gen_device_info_bdw_gt1 = { GEN8_FEATURES, .gt = 1, .is_broadwell = true, .num_slices = 1, .num_subslices = { 2, }, .num_eu_per_subslice = 8, .l3_banks = 2, .max_cs_threads = 42, .urb = { .size = 192, .min_entries = { [MESA_SHADER_VERTEX] = 64, [MESA_SHADER_TESS_EVAL] = 34, }, .max_entries = { [MESA_SHADER_VERTEX] = 2560, [MESA_SHADER_TESS_CTRL] = 504, [MESA_SHADER_TESS_EVAL] = 1536, [MESA_SHADER_GEOMETRY] = 960, }, }, .simulator_id = 11, }; static const struct gen_device_info gen_device_info_bdw_gt2 = { GEN8_FEATURES, .gt = 2, .is_broadwell = true, .num_slices = 1, .num_subslices = { 3, }, .num_eu_per_subslice = 8, .l3_banks = 4, .max_cs_threads = 56, .urb = { .size = 384, .min_entries = { [MESA_SHADER_VERTEX] = 64, [MESA_SHADER_TESS_EVAL] = 34, }, .max_entries = { [MESA_SHADER_VERTEX] = 2560, [MESA_SHADER_TESS_CTRL] = 504, [MESA_SHADER_TESS_EVAL] = 1536, [MESA_SHADER_GEOMETRY] = 960, }, }, .simulator_id = 11, }; static const struct gen_device_info gen_device_info_bdw_gt3 = { GEN8_FEATURES, .gt = 3, .is_broadwell = true, .num_slices = 2, .num_subslices = { 3, 3, }, .num_eu_per_subslice = 8, .l3_banks = 8, .max_cs_threads = 56, .urb = { .size = 384, .min_entries = { [MESA_SHADER_VERTEX] = 64, [MESA_SHADER_TESS_EVAL] = 34, }, .max_entries = { [MESA_SHADER_VERTEX] = 2560, [MESA_SHADER_TESS_CTRL] = 504, [MESA_SHADER_TESS_EVAL] = 1536, [MESA_SHADER_GEOMETRY] = 960, }, }, .simulator_id = 11, }; static const struct gen_device_info gen_device_info_chv = { GEN8_FEATURES, .is_cherryview = 1, .gt = 1, .has_llc = false, .has_integer_dword_mul = false, .num_slices = 1, .num_subslices = { 2, }, .num_eu_per_subslice = 8, .l3_banks = 2, .max_vs_threads = 80, .max_tcs_threads = 80, .max_tes_threads = 80, .max_gs_threads = 80, .max_wm_threads = 128, .max_cs_threads = 6 * 7, .urb = { .size = 192, .min_entries = { [MESA_SHADER_VERTEX] = 34, [MESA_SHADER_TESS_EVAL] = 34, }, .max_entries = { [MESA_SHADER_VERTEX] = 640, [MESA_SHADER_TESS_CTRL] = 80, [MESA_SHADER_TESS_EVAL] = 384, [MESA_SHADER_GEOMETRY] = 256, }, }, .simulator_id = 13, }; #define GEN9_HW_INFO \ .gen = 9, \ .max_vs_threads = 336, \ .max_gs_threads = 336, \ .max_tcs_threads = 336, \ .max_tes_threads = 336, \ .max_cs_threads = 56, \ .timestamp_frequency = 12000000, \ .urb = { \ .size = 384, \ .min_entries = { \ [MESA_SHADER_VERTEX] = 64, \ [MESA_SHADER_TESS_EVAL] = 34, \ }, \ .max_entries = { \ [MESA_SHADER_VERTEX] = 1856, \ [MESA_SHADER_TESS_CTRL] = 672, \ [MESA_SHADER_TESS_EVAL] = 1120, \ [MESA_SHADER_GEOMETRY] = 640, \ }, \ } #define GEN9_LP_FEATURES \ GEN8_FEATURES, \ GEN9_HW_INFO, \ .has_integer_dword_mul = false, \ .gt = 1, \ .has_llc = false, \ .has_sample_with_hiz = true, \ .num_slices = 1, \ .num_thread_per_eu = 6, \ .max_vs_threads = 112, \ .max_tcs_threads = 112, \ .max_tes_threads = 112, \ .max_gs_threads = 112, \ .max_cs_threads = 6 * 6, \ .timestamp_frequency = 19200000, \ .urb = { \ .size = 192, \ .min_entries = { \ [MESA_SHADER_VERTEX] = 34, \ [MESA_SHADER_TESS_EVAL] = 34, \ }, \ .max_entries = { \ [MESA_SHADER_VERTEX] = 704, \ [MESA_SHADER_TESS_CTRL] = 256, \ [MESA_SHADER_TESS_EVAL] = 416, \ [MESA_SHADER_GEOMETRY] = 256, \ }, \ } #define GEN9_LP_FEATURES_3X6 \ GEN9_LP_FEATURES, \ .num_subslices = { 3, }, \ .num_eu_per_subslice = 6 #define GEN9_LP_FEATURES_2X6 \ GEN9_LP_FEATURES, \ .num_subslices = { 2, }, \ .num_eu_per_subslice = 6, \ .max_vs_threads = 56, \ .max_tcs_threads = 56, \ .max_tes_threads = 56, \ .max_gs_threads = 56, \ .max_cs_threads = 6 * 6, \ .urb = { \ .size = 128, \ .min_entries = { \ [MESA_SHADER_VERTEX] = 34, \ [MESA_SHADER_TESS_EVAL] = 34, \ }, \ .max_entries = { \ [MESA_SHADER_VERTEX] = 352, \ [MESA_SHADER_TESS_CTRL] = 128, \ [MESA_SHADER_TESS_EVAL] = 208, \ [MESA_SHADER_GEOMETRY] = 128, \ }, \ } #define GEN9_FEATURES \ GEN8_FEATURES, \ GEN9_HW_INFO, \ .has_sample_with_hiz = true static const struct gen_device_info gen_device_info_skl_gt1 = { GEN9_FEATURES, .gt = 1, .is_skylake = true, .num_slices = 1, .num_subslices = { 2, }, .num_eu_per_subslice = 6, .l3_banks = 2, .urb.size = 192, /* GT1 seems to have a bug in the top of the pipe (VF/VS?) fixed functions * leading to some vertices to go missing if we use too much URB. */ .urb.max_entries[MESA_SHADER_VERTEX] = 928, .simulator_id = 12, }; static const struct gen_device_info gen_device_info_skl_gt2 = { GEN9_FEATURES, .gt = 2, .is_skylake = true, .num_slices = 1, .num_subslices = { 3, }, .num_eu_per_subslice = 8, .l3_banks = 4, .simulator_id = 12, }; static const struct gen_device_info gen_device_info_skl_gt3 = { GEN9_FEATURES, .gt = 3, .is_skylake = true, .num_slices = 2, .num_subslices = { 3, 3, }, .num_eu_per_subslice = 8, .l3_banks = 8, .simulator_id = 12, }; static const struct gen_device_info gen_device_info_skl_gt4 = { GEN9_FEATURES, .gt = 4, .is_skylake = true, .num_slices = 3, .num_subslices = { 3, 3, 3, }, .num_eu_per_subslice = 8, .l3_banks = 12, /* From the "L3 Allocation and Programming" documentation: * * "URB is limited to 1008KB due to programming restrictions. This is not a * restriction of the L3 implementation, but of the FF and other clients. * Therefore, in a GT4 implementation it is possible for the programmed * allocation of the L3 data array to provide 3*384KB=1152KB for URB, but * only 1008KB of this will be used." */ .urb.size = 1008 / 3, .simulator_id = 12, }; static const struct gen_device_info gen_device_info_bxt = { GEN9_LP_FEATURES_3X6, .is_broxton = true, .l3_banks = 2, .simulator_id = 14, }; static const struct gen_device_info gen_device_info_bxt_2x6 = { GEN9_LP_FEATURES_2X6, .is_broxton = true, .l3_banks = 1, .simulator_id = 14, }; /* * Note: for all KBL SKUs, the PRM says SKL for GS entries, not SKL+. * There's no KBL entry. Using the default SKL (GEN9) GS entries value. */ static const struct gen_device_info gen_device_info_kbl_gt1 = { GEN9_FEATURES, .is_kabylake = true, .gt = 1, .max_cs_threads = 7 * 6, .urb.size = 192, .num_slices = 1, .num_subslices = { 2, }, .num_eu_per_subslice = 6, .l3_banks = 2, /* GT1 seems to have a bug in the top of the pipe (VF/VS?) fixed functions * leading to some vertices to go missing if we use too much URB. */ .urb.max_entries[MESA_SHADER_VERTEX] = 928, .simulator_id = 16, }; static const struct gen_device_info gen_device_info_kbl_gt1_5 = { GEN9_FEATURES, .is_kabylake = true, .gt = 1, .max_cs_threads = 7 * 6, .num_slices = 1, .num_subslices = { 3, }, .num_eu_per_subslice = 6, .l3_banks = 4, .simulator_id = 16, }; static const struct gen_device_info gen_device_info_kbl_gt2 = { GEN9_FEATURES, .is_kabylake = true, .gt = 2, .num_slices = 1, .num_subslices = { 3, }, .num_eu_per_subslice = 8, .l3_banks = 4, .simulator_id = 16, }; static const struct gen_device_info gen_device_info_kbl_gt3 = { GEN9_FEATURES, .is_kabylake = true, .gt = 3, .num_slices = 2, .num_subslices = { 3, 3, }, .num_eu_per_subslice = 8, .l3_banks = 8, .simulator_id = 16, }; static const struct gen_device_info gen_device_info_kbl_gt4 = { GEN9_FEATURES, .is_kabylake = true, .gt = 4, /* * From the "L3 Allocation and Programming" documentation: * * "URB is limited to 1008KB due to programming restrictions. This * is not a restriction of the L3 implementation, but of the FF and * other clients. Therefore, in a GT4 implementation it is * possible for the programmed allocation of the L3 data array to * provide 3*384KB=1152KB for URB, but only 1008KB of this * will be used." */ .urb.size = 1008 / 3, .num_slices = 3, .num_subslices = { 3, 3, 3, }, .num_eu_per_subslice = 8, .l3_banks = 12, .simulator_id = 16, }; static const struct gen_device_info gen_device_info_glk = { GEN9_LP_FEATURES_3X6, .is_geminilake = true, .l3_banks = 2, .simulator_id = 17, }; static const struct gen_device_info gen_device_info_glk_2x6 = { GEN9_LP_FEATURES_2X6, .is_geminilake = true, .l3_banks = 2, .simulator_id = 17, }; static const struct gen_device_info gen_device_info_cfl_gt1 = { GEN9_FEATURES, .is_coffeelake = true, .gt = 1, .num_slices = 1, .num_subslices = { 2, }, .num_eu_per_subslice = 6, .l3_banks = 2, .urb.size = 192, /* GT1 seems to have a bug in the top of the pipe (VF/VS?) fixed functions * leading to some vertices to go missing if we use too much URB. */ .urb.max_entries[MESA_SHADER_VERTEX] = 928, .simulator_id = 24, }; static const struct gen_device_info gen_device_info_cfl_gt2 = { GEN9_FEATURES, .is_coffeelake = true, .gt = 2, .num_slices = 1, .num_subslices = { 3, }, .num_eu_per_subslice = 8, .l3_banks = 4, .simulator_id = 24, }; static const struct gen_device_info gen_device_info_cfl_gt3 = { GEN9_FEATURES, .is_coffeelake = true, .gt = 3, .num_slices = 2, .num_subslices = { 3, 3, }, .num_eu_per_subslice = 8, .l3_banks = 8, .simulator_id = 24, }; #define GEN10_HW_INFO \ .gen = 10, \ .num_thread_per_eu = 7, \ .max_vs_threads = 728, \ .max_gs_threads = 432, \ .max_tcs_threads = 432, \ .max_tes_threads = 624, \ .max_cs_threads = 56, \ .timestamp_frequency = 19200000, \ .urb = { \ .size = 256, \ .min_entries = { \ [MESA_SHADER_VERTEX] = 64, \ [MESA_SHADER_TESS_EVAL] = 34, \ }, \ .max_entries = { \ [MESA_SHADER_VERTEX] = 3936, \ [MESA_SHADER_TESS_CTRL] = 896, \ [MESA_SHADER_TESS_EVAL] = 2064, \ [MESA_SHADER_GEOMETRY] = 832, \ }, \ } #define subslices(args...) { args, } #define GEN10_FEATURES(_gt, _slices, _subslices, _l3) \ GEN8_FEATURES, \ GEN10_HW_INFO, \ .has_sample_with_hiz = true, \ .gt = _gt, \ .num_slices = _slices, \ .num_subslices = _subslices, \ .num_eu_per_subslice = 8, \ .l3_banks = _l3 static const struct gen_device_info gen_device_info_cnl_2x8 = { /* GT0.5 */ GEN10_FEATURES(1, 1, subslices(2), 2), .is_cannonlake = true, .simulator_id = 15, }; static const struct gen_device_info gen_device_info_cnl_3x8 = { /* GT1 */ GEN10_FEATURES(1, 1, subslices(3), 3), .is_cannonlake = true, .simulator_id = 15, }; static const struct gen_device_info gen_device_info_cnl_4x8 = { /* GT 1.5 */ GEN10_FEATURES(1, 2, subslices(2, 2), 6), .is_cannonlake = true, .simulator_id = 15, }; static const struct gen_device_info gen_device_info_cnl_5x8 = { /* GT2 */ GEN10_FEATURES(2, 2, subslices(3, 2), 6), .is_cannonlake = true, .simulator_id = 15, }; #define GEN11_HW_INFO \ .gen = 11, \ .has_pln = false, \ .max_vs_threads = 364, \ .max_gs_threads = 224, \ .max_tcs_threads = 224, \ .max_tes_threads = 364, \ .max_cs_threads = 56 #define GEN11_FEATURES(_gt, _slices, _subslices, _l3) \ GEN8_FEATURES, \ GEN11_HW_INFO, \ .has_64bit_types = false, \ .has_integer_dword_mul = false, \ .has_sample_with_hiz = false, \ .gt = _gt, .num_slices = _slices, .l3_banks = _l3, \ .num_subslices = _subslices, \ .num_eu_per_subslice = 8 #define GEN11_URB_MIN_MAX_ENTRIES \ .min_entries = { \ [MESA_SHADER_VERTEX] = 64, \ [MESA_SHADER_TESS_EVAL] = 34, \ }, \ .max_entries = { \ [MESA_SHADER_VERTEX] = 2384, \ [MESA_SHADER_TESS_CTRL] = 1032, \ [MESA_SHADER_TESS_EVAL] = 2384, \ [MESA_SHADER_GEOMETRY] = 1032, \ } static const struct gen_device_info gen_device_info_icl_8x8 = { GEN11_FEATURES(2, 1, subslices(8), 8), .urb = { .size = 1024, GEN11_URB_MIN_MAX_ENTRIES, }, .simulator_id = 19, }; static const struct gen_device_info gen_device_info_icl_6x8 = { GEN11_FEATURES(1, 1, subslices(6), 6), .urb = { .size = 768, GEN11_URB_MIN_MAX_ENTRIES, }, .simulator_id = 19, }; static const struct gen_device_info gen_device_info_icl_4x8 = { GEN11_FEATURES(1, 1, subslices(4), 6), .urb = { .size = 768, GEN11_URB_MIN_MAX_ENTRIES, }, .simulator_id = 19, }; static const struct gen_device_info gen_device_info_icl_1x8 = { GEN11_FEATURES(1, 1, subslices(1), 6), .urb = { .size = 768, GEN11_URB_MIN_MAX_ENTRIES, }, .simulator_id = 19, }; static const struct gen_device_info gen_device_info_ehl_4x8 = { GEN11_FEATURES(1, 1, subslices(4), 4), .is_elkhartlake = true, .urb = { .size = 512, .min_entries = { [MESA_SHADER_VERTEX] = 64, [MESA_SHADER_TESS_EVAL] = 34, }, .max_entries = { [MESA_SHADER_VERTEX] = 2384, [MESA_SHADER_TESS_CTRL] = 1032, [MESA_SHADER_TESS_EVAL] = 2384, [MESA_SHADER_GEOMETRY] = 1032, }, }, .disable_ccs_repack = true, .simulator_id = 28, }; /* FIXME: Verfiy below entries when more information is available for this SKU. */ static const struct gen_device_info gen_device_info_ehl_4x4 = { GEN11_FEATURES(1, 1, subslices(4), 4), .is_elkhartlake = true, .urb = { .size = 512, .min_entries = { [MESA_SHADER_VERTEX] = 64, [MESA_SHADER_TESS_EVAL] = 34, }, .max_entries = { [MESA_SHADER_VERTEX] = 2384, [MESA_SHADER_TESS_CTRL] = 1032, [MESA_SHADER_TESS_EVAL] = 2384, [MESA_SHADER_GEOMETRY] = 1032, }, }, .disable_ccs_repack = true, .num_eu_per_subslice = 4, .simulator_id = 28, }; /* FIXME: Verfiy below entries when more information is available for this SKU. */ static const struct gen_device_info gen_device_info_ehl_2x4 = { GEN11_FEATURES(1, 1, subslices(2), 4), .is_elkhartlake = true, .urb = { .size = 512, .min_entries = { [MESA_SHADER_VERTEX] = 64, [MESA_SHADER_TESS_EVAL] = 34, }, .max_entries = { [MESA_SHADER_VERTEX] = 2384, [MESA_SHADER_TESS_CTRL] = 1032, [MESA_SHADER_TESS_EVAL] = 2384, [MESA_SHADER_GEOMETRY] = 1032, }, }, .disable_ccs_repack = true, .num_eu_per_subslice =4, .simulator_id = 28, }; static void gen_device_info_set_eu_mask(struct gen_device_info *devinfo, unsigned slice, unsigned subslice, unsigned eu_mask) { unsigned subslice_offset = slice * devinfo->eu_slice_stride + subslice * devinfo->eu_subslice_stride; for (unsigned b_eu = 0; b_eu < devinfo->eu_subslice_stride; b_eu++) { devinfo->eu_masks[subslice_offset + b_eu] = (((1U << devinfo->num_eu_per_subslice) - 1) >> (b_eu * 8)) & 0xff; } } /* Generate slice/subslice/eu masks from number of * slices/subslices/eu_per_subslices in the per generation/gt gen_device_info * structure. * * These can be overridden with values reported by the kernel either from * getparam SLICE_MASK/SUBSLICE_MASK values or from the kernel version 4.17+ * through the i915 query uapi. */ static void fill_masks(struct gen_device_info *devinfo) { devinfo->slice_masks = (1U << devinfo->num_slices) - 1; /* Subslice masks */ unsigned max_subslices = 0; for (int s = 0; s < devinfo->num_slices; s++) max_subslices = MAX2(devinfo->num_subslices[s], max_subslices); devinfo->subslice_slice_stride = DIV_ROUND_UP(max_subslices, 8); for (int s = 0; s < devinfo->num_slices; s++) { devinfo->subslice_masks[s * devinfo->subslice_slice_stride] = (1U << devinfo->num_subslices[s]) - 1; } /* EU masks */ devinfo->eu_subslice_stride = DIV_ROUND_UP(devinfo->num_eu_per_subslice, 8); devinfo->eu_slice_stride = max_subslices * devinfo->eu_subslice_stride; for (int s = 0; s < devinfo->num_slices; s++) { for (int ss = 0; ss < devinfo->num_subslices[s]; ss++) { gen_device_info_set_eu_mask(devinfo, s, ss, (1U << devinfo->num_eu_per_subslice) - 1); } } } static void reset_masks(struct gen_device_info *devinfo) { devinfo->subslice_slice_stride = 0; devinfo->eu_subslice_stride = 0; devinfo->eu_slice_stride = 0; devinfo->num_slices = 0; devinfo->num_eu_per_subslice = 0; memset(devinfo->num_subslices, 0, sizeof(devinfo->num_subslices)); memset(&devinfo->slice_masks, 0, sizeof(devinfo->slice_masks)); memset(devinfo->subslice_masks, 0, sizeof(devinfo->subslice_masks)); memset(devinfo->eu_masks, 0, sizeof(devinfo->eu_masks)); memset(devinfo->ppipe_subslices, 0, sizeof(devinfo->ppipe_subslices)); } static void update_from_topology(struct gen_device_info *devinfo, const struct drm_i915_query_topology_info *topology) { reset_masks(devinfo); devinfo->subslice_slice_stride = topology->subslice_stride; devinfo->eu_subslice_stride = DIV_ROUND_UP(topology->max_eus_per_subslice, 8); devinfo->eu_slice_stride = topology->max_subslices * devinfo->eu_subslice_stride; assert(sizeof(devinfo->slice_masks) >= DIV_ROUND_UP(topology->max_slices, 8)); memcpy(&devinfo->slice_masks, topology->data, DIV_ROUND_UP(topology->max_slices, 8)); devinfo->num_slices = __builtin_popcount(devinfo->slice_masks); uint32_t subslice_mask_len = topology->max_slices * topology->subslice_stride; assert(sizeof(devinfo->subslice_masks) >= subslice_mask_len); memcpy(devinfo->subslice_masks, &topology->data[topology->subslice_offset], subslice_mask_len); uint32_t n_subslices = 0; for (int s = 0; s < topology->max_slices; s++) { if ((devinfo->slice_masks & (1 << s)) == 0) continue; for (int b = 0; b < devinfo->subslice_slice_stride; b++) { devinfo->num_subslices[s] += __builtin_popcount(devinfo->subslice_masks[s * devinfo->subslice_slice_stride + b]); } n_subslices += devinfo->num_subslices[s]; } assert(n_subslices > 0); if (devinfo->gen == 11) { /* On ICL we only have one slice */ assert(devinfo->slice_masks == 1); /* Count the number of subslices on each pixel pipe. Assume that * subslices 0-3 are on pixel pipe 0, and 4-7 are on pixel pipe 1. */ unsigned subslices = devinfo->subslice_masks[0]; unsigned ss = 0; while (subslices > 0) { if (subslices & 1) devinfo->ppipe_subslices[ss >= 4 ? 1 : 0] += 1; subslices >>= 1; ss++; } } uint32_t eu_mask_len = topology->eu_stride * topology->max_subslices * topology->max_slices; assert(sizeof(devinfo->eu_masks) >= eu_mask_len); memcpy(devinfo->eu_masks, &topology->data[topology->eu_offset], eu_mask_len); uint32_t n_eus = 0; for (int b = 0; b < eu_mask_len; b++) n_eus += __builtin_popcount(devinfo->eu_masks[b]); devinfo->num_eu_per_subslice = DIV_ROUND_UP(n_eus, n_subslices); } static bool update_from_masks(struct gen_device_info *devinfo, uint32_t slice_mask, uint32_t subslice_mask, uint32_t n_eus) { struct drm_i915_query_topology_info *topology; assert((slice_mask & 0xff) == slice_mask); size_t data_length = 100; topology = calloc(1, sizeof(*topology) + data_length); if (!topology) return false; topology->max_slices = util_last_bit(slice_mask); topology->max_subslices = util_last_bit(subslice_mask); topology->subslice_offset = DIV_ROUND_UP(topology->max_slices, 8); topology->subslice_stride = DIV_ROUND_UP(topology->max_subslices, 8); uint32_t n_subslices = __builtin_popcount(slice_mask) * __builtin_popcount(subslice_mask); uint32_t num_eu_per_subslice = DIV_ROUND_UP(n_eus, n_subslices); uint32_t eu_mask = (1U << num_eu_per_subslice) - 1; topology->eu_offset = topology->subslice_offset + DIV_ROUND_UP(topology->max_subslices, 8); topology->eu_stride = DIV_ROUND_UP(num_eu_per_subslice, 8); /* Set slice mask in topology */ for (int b = 0; b < topology->subslice_offset; b++) topology->data[b] = (slice_mask >> (b * 8)) & 0xff; for (int s = 0; s < topology->max_slices; s++) { /* Set subslice mask in topology */ for (int b = 0; b < topology->subslice_stride; b++) { int subslice_offset = topology->subslice_offset + s * topology->subslice_stride + b; topology->data[subslice_offset] = (subslice_mask >> (b * 8)) & 0xff; } /* Set eu mask in topology */ for (int ss = 0; ss < topology->max_subslices; ss++) { for (int b = 0; b < topology->eu_stride; b++) { int eu_offset = topology->eu_offset + (s * topology->max_subslices + ss) * topology->eu_stride + b; topology->data[eu_offset] = (eu_mask >> (b * 8)) & 0xff; } } } update_from_topology(devinfo, topology); free(topology); return true; } static bool getparam(int fd, uint32_t param, int *value) { int tmp; struct drm_i915_getparam gp = { .param = param, .value = &tmp, }; int ret = gen_ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp); if (ret != 0) return false; *value = tmp; return true; } bool gen_get_device_info_from_pci_id(int pci_id, struct gen_device_info *devinfo) { switch (pci_id) { #undef CHIPSET #define CHIPSET(id, family, name) \ case id: *devinfo = gen_device_info_##family; break; #include "pci_ids/i965_pci_ids.h" #include "pci_ids/iris_pci_ids.h" default: fprintf(stderr, "Driver does not support the 0x%x PCI ID.\n", pci_id); return false; } fill_masks(devinfo); /* From the Skylake PRM, 3DSTATE_PS::Scratch Space Base Pointer: * * "Scratch Space per slice is computed based on 4 sub-slices. SW must * allocate scratch space enough so that each slice has 4 slices allowed." * * The equivalent internal documentation says that this programming note * applies to all Gen9+ platforms. * * The hardware typically calculates the scratch space pointer by taking * the base address, and adding per-thread-scratch-space * thread ID. * Extra padding can be necessary depending how the thread IDs are * calculated for a particular shader stage. */ switch(devinfo->gen) { case 9: case 10: devinfo->max_wm_threads = 64 /* threads-per-PSD */ * devinfo->num_slices * 4; /* effective subslices per slice */ break; case 11: devinfo->max_wm_threads = 128 /* threads-per-PSD */ * devinfo->num_slices * 8; /* subslices per slice */ break; default: break; } assert(devinfo->num_slices <= ARRAY_SIZE(devinfo->num_subslices)); devinfo->chipset_id = pci_id; return true; } const char * gen_get_device_name(int devid) { switch (devid) { #undef CHIPSET #define CHIPSET(id, family, name) case id: return name; #include "pci_ids/i965_pci_ids.h" #include "pci_ids/iris_pci_ids.h" default: return NULL; } } /** * for gen8/gen9, SLICE_MASK/SUBSLICE_MASK can be used to compute the topology * (kernel 4.13+) */ static bool getparam_topology(struct gen_device_info *devinfo, int fd) { int slice_mask = 0; if (!getparam(fd, I915_PARAM_SLICE_MASK, &slice_mask)) return false; int n_eus; if (!getparam(fd, I915_PARAM_EU_TOTAL, &n_eus)) return false; int subslice_mask = 0; if (!getparam(fd, I915_PARAM_SUBSLICE_MASK, &subslice_mask)) return false; return update_from_masks(devinfo, slice_mask, subslice_mask, n_eus); } /** * preferred API for updating the topology in devinfo (kernel 4.17+) */ static bool query_topology(struct gen_device_info *devinfo, int fd) { struct drm_i915_query_item item = { .query_id = DRM_I915_QUERY_TOPOLOGY_INFO, }; struct drm_i915_query query = { .num_items = 1, .items_ptr = (uintptr_t) &item, }; if (gen_ioctl(fd, DRM_IOCTL_I915_QUERY, &query)) return false; if (item.length < 0) return false; struct drm_i915_query_topology_info *topo_info = (struct drm_i915_query_topology_info *) calloc(1, item.length); item.data_ptr = (uintptr_t) topo_info; if (gen_ioctl(fd, DRM_IOCTL_I915_QUERY, &query) || item.length <= 0) return false; update_from_topology(devinfo, topo_info); free(topo_info); return true; } bool gen_get_device_info_from_fd(int fd, struct gen_device_info *devinfo) { int devid = get_pci_device_id_override(); if (devid > 0) { if (!gen_get_device_info_from_pci_id(devid, devinfo)) return false; devinfo->no_hw = true; } else { /* query the device id */ if (!getparam(fd, I915_PARAM_CHIPSET_ID, &devid)) return false; if (!gen_get_device_info_from_pci_id(devid, devinfo)) return false; devinfo->no_hw = false; } /* remaining initializion queries the kernel for device info */ if (devinfo->no_hw) return true; int timestamp_frequency; if (getparam(fd, I915_PARAM_CS_TIMESTAMP_FREQUENCY, ×tamp_frequency)) devinfo->timestamp_frequency = timestamp_frequency; else if (devinfo->gen >= 10) /* gen10 and later requires the timestamp_frequency to be updated */ return false; if (!getparam(fd, I915_PARAM_REVISION, &devinfo->revision)) return false; if (!query_topology(devinfo, fd)) { if (devinfo->gen >= 10) { /* topology uAPI required for CNL+ (kernel 4.17+) */ return false; } /* else use the kernel 4.13+ api for gen8+. For older kernels, topology * will be wrong, affecting GPU metrics. In this case, fail silently. */ getparam_topology(devinfo, fd); } return true; } ================================================ FILE: mesa/src/intel/dev/gen_device_info.h ================================================ /* * Copyright © 2013 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * */ #ifndef GEN_DEVICE_INFO_H #define GEN_DEVICE_INFO_H #include #include #include "util/macros.h" #ifdef __cplusplus extern "C" { #endif struct drm_i915_query_topology_info; #define GEN_DEVICE_MAX_SLICES (6) /* Maximum on gen10 */ #define GEN_DEVICE_MAX_SUBSLICES (8) /* Maximum on gen11 */ #define GEN_DEVICE_MAX_EUS_PER_SUBSLICE (10) /* Maximum on Haswell */ #define GEN_DEVICE_MAX_PIXEL_PIPES (2) /* Maximum on gen11 */ /** * Intel hardware information and quirks */ struct gen_device_info { int gen; /**< Generation number: 4, 5, 6, 7, ... */ int revision; int gt; bool is_g4x; bool is_ivybridge; bool is_baytrail; bool is_haswell; bool is_broadwell; bool is_cherryview; bool is_skylake; bool is_broxton; bool is_kabylake; bool is_geminilake; bool is_coffeelake; bool is_cannonlake; bool is_elkhartlake; bool has_hiz_and_separate_stencil; bool must_use_separate_stencil; bool has_sample_with_hiz; bool has_llc; bool has_pln; bool has_64bit_types; bool has_integer_dword_mul; bool has_compr4; bool has_surface_tile_offset; bool supports_simd16_3src; bool has_resource_streamer; bool disable_ccs_repack; bool has_aux_map; /** * \name Intel hardware quirks * @{ */ bool has_negative_rhw_bug; /** * Some versions of Gen hardware don't do centroid interpolation correctly * on unlit pixels, causing incorrect values for derivatives near triangle * edges. Enabling this flag causes the fragment shader to use * non-centroid interpolation for unlit pixels, at the expense of two extra * fragment shader instructions. */ bool needs_unlit_centroid_workaround; /** @} */ /** * \name GPU hardware limits * * In general, you can find shader thread maximums by looking at the "Maximum * Number of Threads" field in the Intel PRM description of the 3DSTATE_VS, * 3DSTATE_GS, 3DSTATE_HS, 3DSTATE_DS, and 3DSTATE_PS commands. URB entry * limits come from the "Number of URB Entries" field in the * 3DSTATE_URB_VS command and friends. * * These fields are used to calculate the scratch space to allocate. The * amount of scratch space can be larger without being harmful on modern * GPUs, however, prior to Haswell, programming the maximum number of threads * to greater than the hardware maximum would cause GPU performance to tank. * * @{ */ /** * Total number of slices present on the device whether or not they've been * fused off. * * XXX: CS thread counts are limited by the inability to do cross subslice * communication. It is the effectively the number of logical threads which * can be executed in a subslice. Fuse configurations may cause this number * to change, so we program @max_cs_threads as the lower maximum. */ unsigned num_slices; /** * Number of subslices for each slice (used to be uniform until CNL). */ unsigned num_subslices[GEN_DEVICE_MAX_SUBSLICES]; /** * Number of subslices on each pixel pipe (ICL). */ unsigned ppipe_subslices[GEN_DEVICE_MAX_PIXEL_PIPES]; /** * Upper bound of number of EU per subslice (some SKUs might have just 1 EU * fused across all subslices, like 47 EUs, in which case this number won't * be acurate for one subslice). */ unsigned num_eu_per_subslice; /** * Number of threads per eu, varies between 4 and 8 between generations. */ unsigned num_thread_per_eu; /** * A bit mask of the slices available. */ uint8_t slice_masks; /** * An array of bit mask of the subslices available, use subslice_slice_stride * to access this array. */ uint8_t subslice_masks[GEN_DEVICE_MAX_SLICES * DIV_ROUND_UP(GEN_DEVICE_MAX_SUBSLICES, 8)]; /** * An array of bit mask of EUs available, use eu_slice_stride & * eu_subslice_stride to access this array. */ uint8_t eu_masks[GEN_DEVICE_MAX_SLICES * GEN_DEVICE_MAX_SUBSLICES * DIV_ROUND_UP(GEN_DEVICE_MAX_EUS_PER_SUBSLICE, 8)]; /** * Stride to access subslice_masks[]. */ uint16_t subslice_slice_stride; /** * Strides to access eu_masks[]. */ uint16_t eu_slice_stride; uint16_t eu_subslice_stride; unsigned l3_banks; unsigned max_vs_threads; /**< Maximum Vertex Shader threads */ unsigned max_tcs_threads; /**< Maximum Hull Shader threads */ unsigned max_tes_threads; /**< Maximum Domain Shader threads */ unsigned max_gs_threads; /**< Maximum Geometry Shader threads. */ /** * Theoretical maximum number of Pixel Shader threads. * * PSD means Pixel Shader Dispatcher. On modern Intel GPUs, hardware will * automatically scale pixel shader thread count, based on a single value * programmed into 3DSTATE_PS. * * To calculate the maximum number of threads for Gen8 beyond (which have * multiple Pixel Shader Dispatchers): * * - Look up 3DSTATE_PS and find "Maximum Number of Threads Per PSD" * - Usually there's only one PSD per subslice, so use the number of * subslices for number of PSDs. * - For max_wm_threads, the total should be PSD threads * #PSDs. */ unsigned max_wm_threads; /** * Maximum Compute Shader threads. * * Thread count * number of EUs per subslice */ unsigned max_cs_threads; struct { /** * Hardware default URB size. * * The units this is expressed in are somewhat inconsistent: 512b units * on Gen4-5, KB on Gen6-7, and KB times the slice count on Gen8+. * * Look up "URB Size" in the "Device Attributes" page, and take the * maximum. Look up the slice count for each GT SKU on the same page. * urb.size = URB Size (kbytes) / slice count */ unsigned size; /** * The minimum number of URB entries. See the 3DSTATE_URB_ docs. */ unsigned min_entries[4]; /** * The maximum number of URB entries. See the 3DSTATE_URB_ docs. */ unsigned max_entries[4]; } urb; /** * For the longest time the timestamp frequency for Gen's timestamp counter * could be assumed to be 12.5MHz, where the least significant bit neatly * corresponded to 80 nanoseconds. * * Since Gen9 the numbers aren't so round, with a a frequency of 12MHz for * SKL (or scale factor of 83.33333333) and a frequency of 19200000Hz for * BXT. * * For simplicty to fit with the current code scaling by a single constant * to map from raw timestamps to nanoseconds we now do the conversion in * floating point instead of integer arithmetic. * * In general it's probably worth noting that the documented constants we * have for the per-platform timestamp frequencies aren't perfect and * shouldn't be trusted for scaling and comparing timestamps with a large * delta. * * E.g. with crude testing on my system using the 'correct' scale factor I'm * seeing a drift of ~2 milliseconds per second. */ uint64_t timestamp_frequency; /** * ID to put into the .aub files. */ int simulator_id; /** * holds the pci device id */ uint32_t chipset_id; /** * no_hw is true when the chipset_id pci device id has been overridden */ bool no_hw; /** @} */ }; #define gen_device_info_is_9lp(devinfo) \ ((devinfo)->is_broxton || (devinfo)->is_geminilake) static inline bool gen_device_info_subslice_available(const struct gen_device_info *devinfo, int slice, int subslice) { return (devinfo->subslice_masks[slice * devinfo->subslice_slice_stride + subslice / 8] & (1U << (subslice % 8))) != 0; } int gen_device_name_to_pci_device_id(const char *name); const char *gen_get_device_name(int devid); static inline uint64_t gen_device_info_timebase_scale(const struct gen_device_info *devinfo, uint64_t gpu_timestamp) { return (1000000000ull * gpu_timestamp) / devinfo->timestamp_frequency; } bool gen_get_device_info_from_fd(int fh, struct gen_device_info *devinfo); bool gen_get_device_info_from_pci_id(int pci_id, struct gen_device_info *devinfo); #ifdef __cplusplus } #endif #endif /* GEN_DEVICE_INFO_H */ ================================================ FILE: mesa/src/mesa/main/compiler.h ================================================ /* * Mesa 3-D graphics library * * Copyright (C) 1999-2008 Brian Paul All Rights Reserved. * Copyright (C) 2009 VMware, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * \file compiler.h * Compiler-related stuff. */ #ifndef COMPILER_H #define COMPILER_H #include #include "util/macros.h" #include "c99_compat.h" /* inline, __func__, etc. */ /** * Either define MESA_BIG_ENDIAN or MESA_LITTLE_ENDIAN, and CPU_TO_LE32. * Do not use these unless absolutely necessary! * Try to use a runtime test instead. * For now, only used by some DRI hardware drivers for color/texel packing. */ #if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN #if defined(__linux__) #include #define CPU_TO_LE32( x ) bswap_32( x ) #elif defined(__APPLE__) #include #define CPU_TO_LE32( x ) CFSwapInt32HostToLittle( x ) #elif defined(__OpenBSD__) #include #define CPU_TO_LE32( x ) htole32( x ) #else /*__linux__ */ #include #define CPU_TO_LE32( x ) bswap32( x ) #endif /*__linux__*/ #define MESA_BIG_ENDIAN 1 #else #define CPU_TO_LE32( x ) ( x ) #define MESA_LITTLE_ENDIAN 1 #endif #define LE32_TO_CPU( x ) CPU_TO_LE32( x ) #define IEEE_ONE 0x3f800000 #endif /* COMPILER_H */ ================================================ FILE: mesa/src/mesa/main/hash.h ================================================ /** * \file hash.h * Generic hash table. */ /* * Mesa 3-D graphics library * * Copyright (C) 1999-2006 Brian Paul All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef HASH_H #define HASH_H #include typedef unsigned int GLuint; typedef bool GLboolean; #include "c11/threads.h" /** * Magic GLuint object name that gets stored outside of the struct hash_table. * * The hash table needs a particular pointer to be the marker for a key that * was deleted from the table, along with NULL for the "never allocated in the * table" marker. Legacy GL allows any GLuint to be used as a GL object name, * and we use a 1:1 mapping from GLuints to key pointers, so we need to be * able to track a GLuint that happens to match the deleted key outside of * struct hash_table. We tell the hash table to use "1" as the deleted key * value, so that we test the deleted-key-in-the-table path as best we can. */ #define DELETED_KEY_VALUE 1 /** Allocate a structure of type \p T */ #define MALLOC_STRUCT(T) (struct T *) malloc(sizeof(struct T)) /** Allocate and zero a structure of type \p T */ #define CALLOC_STRUCT(T) (struct T *) calloc(1, sizeof(struct T)) /** @{ * Mapping from our use of GLuint as both the key and the hash value to the * hash_table.h API * * There exist many integer hash functions, designed to avoid collisions when * the integers are spread across key space with some patterns. In GL, the * pattern (in the case of glGen*()ed object IDs) is that the keys are unique * contiguous integers starting from 1. Because of that, we just use the key * as the hash value, to minimize the cost of the hash function. If objects * are never deleted, we will never see a collision in the table, because the * table resizes itself when it approaches full, and thus key % table_size == * key. * * The case where we could have collisions for genned objects would be * something like: glGenBuffers(&a, 100); glDeleteBuffers(&a + 50, 50); * glGenBuffers(&b, 100), because objects 1-50 and 101-200 are allocated at * the end of that sequence, instead of 1-150. So far it doesn't appear to be * a problem. */ static inline bool uint_key_compare(const void *a, const void *b) { return a == b; } static inline uint32_t uint_hash(GLuint id) { return id; } static inline uint32_t uint_key_hash(const void *key) { return uint_hash((uintptr_t)key); } static inline void * uint_key(GLuint id) { return (void *)(uintptr_t) id; } /** @} */ /** * The hash table data structure. */ struct _mesa_HashTable { struct hash_table *ht; GLuint MaxKey; /**< highest key inserted so far */ mtx_t Mutex; /**< mutual exclusion lock */ GLboolean InDeleteAll; /**< Debug check */ /** Value that would be in the table for DELETED_KEY_VALUE. */ void *deleted_key_data; }; extern struct _mesa_HashTable *_mesa_NewHashTable(void); extern void _mesa_DeleteHashTable(struct _mesa_HashTable *table); extern void *_mesa_HashLookup(struct _mesa_HashTable *table, GLuint key); extern void _mesa_HashInsert(struct _mesa_HashTable *table, GLuint key, void *data); extern void _mesa_HashRemove(struct _mesa_HashTable *table, GLuint key); /** * Lock the hash table mutex. * * This function should be used when multiple objects need * to be looked up in the hash table, to avoid having to lock * and unlock the mutex each time. * * \param table the hash table. */ static inline void _mesa_HashLockMutex(struct _mesa_HashTable *table) { assert(table); mtx_lock(&table->Mutex); } /** * Unlock the hash table mutex. * * \param table the hash table. */ static inline void _mesa_HashUnlockMutex(struct _mesa_HashTable *table) { assert(table); mtx_unlock(&table->Mutex); } extern void *_mesa_HashLookupLocked(struct _mesa_HashTable *table, GLuint key); extern void _mesa_HashInsertLocked(struct _mesa_HashTable *table, GLuint key, void *data); extern void _mesa_HashRemoveLocked(struct _mesa_HashTable *table, GLuint key); extern void _mesa_HashDeleteAll(struct _mesa_HashTable *table, void (*callback)(GLuint key, void *data, void *userData), void *userData); extern void _mesa_HashWalk(const struct _mesa_HashTable *table, void (*callback)(GLuint key, void *data, void *userData), void *userData); extern void _mesa_HashWalkLocked(const struct _mesa_HashTable *table, void (*callback)(GLuint key, void *data, void *userData), void *userData); extern void _mesa_HashPrint(const struct _mesa_HashTable *table); extern GLuint _mesa_HashFindFreeKeyBlock(struct _mesa_HashTable *table, GLuint numKeys); extern GLuint _mesa_HashNumEntries(const struct _mesa_HashTable *table); extern void _mesa_test_hash_functions(void); #endif ================================================ FILE: mesa/src/util/bitscan.c ================================================ /************************************************************************** * * Copyright 2008 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #include "bitscan.h" #ifdef HAVE___BUILTIN_FFS #elif defined(_MSC_VER) && (_M_IX86 || _M_ARM || _M_AMD64 || _M_IA64) #else int ffs(int i) { int bit = 0; if (!i) return bit; if (!(i & 0xffff)) { bit += 16; i >>= 16; } if (!(i & 0xff)) { bit += 8; i >>= 8; } if (!(i & 0xf)) { bit += 4; i >>= 4; } if (!(i & 0x3)) { bit += 2; i >>= 2; } if (!(i & 0x1)) bit += 1; return bit + 1; } #endif #ifdef HAVE___BUILTIN_FFSLL #elif defined(_MSC_VER) && (_M_AMD64 || _M_ARM || _M_IA64) #else int ffsll(long long int val) { int bit; bit = ffs((unsigned) (val & 0xffffffff)); if (bit != 0) return bit; bit = ffs((unsigned) (val >> 32)); if (bit != 0) return 32 + bit; return 0; } #endif ================================================ FILE: mesa/src/util/bitscan.h ================================================ /************************************************************************** * * Copyright 2008 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #ifndef BITSCAN_H #define BITSCAN_H #include #include #include #include #if defined(_MSC_VER) #include #endif #if defined(__POPCNT__) #include #endif #include "c99_compat.h" #ifdef __cplusplus extern "C" { #endif /** * Find first bit set in word. Least significant bit is 1. * Return 0 if no bits set. */ #ifdef HAVE___BUILTIN_FFS #define ffs __builtin_ffs #elif defined(_MSC_VER) && (_M_IX86 || _M_ARM || _M_AMD64 || _M_IA64) static inline int ffs(int i) { unsigned long index; if (_BitScanForward(&index, i)) return index + 1; else return 0; } #else extern int ffs(int i); #endif #ifdef HAVE___BUILTIN_FFSLL #define ffsll __builtin_ffsll #elif defined(_MSC_VER) && (_M_AMD64 || _M_ARM || _M_IA64) static inline int ffsll(long long int i) { unsigned long index; if (_BitScanForward64(&index, i)) return index + 1; else return 0; } #else extern int ffsll(long long int val); #endif /* Destructively loop over all of the bits in a mask as in: * * while (mymask) { * int i = u_bit_scan(&mymask); * ... process element i * } * */ static inline int u_bit_scan(unsigned *mask) { const int i = ffs(*mask) - 1; *mask ^= (1u << i); return i; } static inline int u_bit_scan64(uint64_t *mask) { const int i = ffsll(*mask) - 1; *mask ^= (((uint64_t)1) << i); return i; } /* Determine if an unsigned value is a power of two. * * \note * Zero is treated as a power of two. */ static inline bool util_is_power_of_two_or_zero(unsigned v) { return (v & (v - 1)) == 0; } /* Determine if an uint64_t value is a power of two. * * \note * Zero is treated as a power of two. */ static inline bool util_is_power_of_two_or_zero64(uint64_t v) { return (v & (v - 1)) == 0; } /* Determine if an unsigned value is a power of two. * * \note * Zero is \b not treated as a power of two. */ static inline bool util_is_power_of_two_nonzero(unsigned v) { /* __POPCNT__ is different from HAVE___BUILTIN_POPCOUNT. The latter * indicates the existence of the __builtin_popcount function. The former * indicates that _mm_popcnt_u32 exists and is a native instruction. * * The other alternative is to use SSE 4.2 compile-time flags. This has * two drawbacks. First, there is currently no build infrastructure for * SSE 4.2 (only 4.1), so that would have to be added. Second, some AMD * CPUs support POPCNT but not SSE 4.2 (e.g., Barcelona). */ #ifdef __POPCNT__ return _mm_popcnt_u32(v) == 1; #else return v != 0 && (v & (v - 1)) == 0; #endif } /* For looping over a bitmask when you want to loop over consecutive bits * manually, for example: * * while (mask) { * int start, count, i; * * u_bit_scan_consecutive_range(&mask, &start, &count); * * for (i = 0; i < count; i++) * ... process element (start+i) * } */ static inline void u_bit_scan_consecutive_range(unsigned *mask, int *start, int *count) { if (*mask == 0xffffffff) { *start = 0; *count = 32; *mask = 0; return; } *start = ffs(*mask) - 1; *count = ffs(~(*mask >> *start)) - 1; *mask &= ~(((1u << *count) - 1) << *start); } static inline void u_bit_scan_consecutive_range64(uint64_t *mask, int *start, int *count) { if (*mask == ~0ull) { *start = 0; *count = 64; *mask = 0; return; } *start = ffsll(*mask) - 1; *count = ffsll(~(*mask >> *start)) - 1; *mask &= ~(((((uint64_t)1) << *count) - 1) << *start); } /** * Find last bit set in a word. The least significant bit is 1. * Return 0 if no bits are set. * Essentially ffs() in the reverse direction. */ static inline unsigned util_last_bit(unsigned u) { #if defined(HAVE___BUILTIN_CLZ) return u == 0 ? 0 : 32 - __builtin_clz(u); #elif defined(_MSC_VER) && (_M_IX86 || _M_ARM || _M_AMD64 || _M_IA64) unsigned long index; if (_BitScanReverse(&index, u)) return index + 1; else return 0; #else unsigned r = 0; while (u) { r++; u >>= 1; } return r; #endif } /** * Find last bit set in a word. The least significant bit is 1. * Return 0 if no bits are set. * Essentially ffsll() in the reverse direction. */ static inline unsigned util_last_bit64(uint64_t u) { #if defined(HAVE___BUILTIN_CLZLL) return u == 0 ? 0 : 64 - __builtin_clzll(u); #elif defined(_MSC_VER) && (_M_AMD64 || _M_ARM || _M_IA64) unsigned long index; if (_BitScanReverse64(&index, u)) return index + 1; else return 0; #else unsigned r = 0; while (u) { r++; u >>= 1; } return r; #endif } /** * Find last bit in a word that does not match the sign bit. The least * significant bit is 1. * Return 0 if no bits are set. */ static inline unsigned util_last_bit_signed(int i) { if (i >= 0) return util_last_bit(i); else return util_last_bit(~(unsigned)i); } /* Returns a bitfield in which the first count bits starting at start are * set. */ static inline unsigned u_bit_consecutive(unsigned start, unsigned count) { assert(start + count <= 32); if (count == 32) return ~0; return ((1u << count) - 1) << start; } static inline uint64_t u_bit_consecutive64(unsigned start, unsigned count) { assert(start + count <= 64); if (count == 64) return ~(uint64_t)0; return (((uint64_t)1 << count) - 1) << start; } #ifdef __cplusplus } #endif #endif /* BITSCAN_H */ ================================================ FILE: mesa/src/util/bitset.h ================================================ /* * Mesa 3-D graphics library * * Copyright (C) 2006 Brian Paul All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * \file bitset.h * \brief Bitset of arbitrary size definitions. * \author Michal Krol */ #ifndef BITSET_H #define BITSET_H #include "util/bitscan.h" #include "util/macros.h" /**************************************************************************** * generic bitset implementation */ #define BITSET_WORD unsigned int #define BITSET_WORDBITS (sizeof (BITSET_WORD) * 8) /* bitset declarations */ #define BITSET_WORDS(bits) (((bits) + BITSET_WORDBITS - 1) / BITSET_WORDBITS) #define BITSET_DECLARE(name, bits) BITSET_WORD name[BITSET_WORDS(bits)] /* bitset operations */ #define BITSET_COPY(x, y) memcpy( (x), (y), sizeof (x) ) #define BITSET_EQUAL(x, y) (memcmp( (x), (y), sizeof (x) ) == 0) #define BITSET_ZERO(x) memset( (x), 0, sizeof (x) ) #define BITSET_ONES(x) memset( (x), 0xff, sizeof (x) ) #define BITSET_BITWORD(b) ((b) / BITSET_WORDBITS) #define BITSET_BIT(b) (1u << ((b) % BITSET_WORDBITS)) /* single bit operations */ #define BITSET_TEST(x, b) ((x)[BITSET_BITWORD(b)] & BITSET_BIT(b)) #define BITSET_SET(x, b) ((x)[BITSET_BITWORD(b)] |= BITSET_BIT(b)) #define BITSET_CLEAR(x, b) ((x)[BITSET_BITWORD(b)] &= ~BITSET_BIT(b)) #define BITSET_MASK(b) ((b) == BITSET_WORDBITS ? ~0 : BITSET_BIT(b) - 1) #define BITSET_RANGE(b, e) (BITSET_MASK((e) + 1) & ~BITSET_MASK(b)) /* bit range operations */ #define BITSET_TEST_RANGE(x, b, e) \ (BITSET_BITWORD(b) == BITSET_BITWORD(e) ? \ ((x)[BITSET_BITWORD(b)] & BITSET_RANGE(b, e)) : \ (assert (!"BITSET_TEST_RANGE: bit range crosses word boundary"), 0)) #define BITSET_SET_RANGE(x, b, e) \ (BITSET_BITWORD(b) == BITSET_BITWORD(e) ? \ ((x)[BITSET_BITWORD(b)] |= BITSET_RANGE(b, e)) : \ (assert (!"BITSET_SET_RANGE: bit range crosses word boundary"), 0)) #define BITSET_CLEAR_RANGE(x, b, e) \ (BITSET_BITWORD(b) == BITSET_BITWORD(e) ? \ ((x)[BITSET_BITWORD(b)] &= ~BITSET_RANGE(b, e)) : \ (assert (!"BITSET_CLEAR_RANGE: bit range crosses word boundary"), 0)) /* Get first bit set in a bitset. */ static inline int __bitset_ffs(const BITSET_WORD *x, int n) { int i; for (i = 0; i < n; i++) { if (x[i]) return ffs(x[i]) + BITSET_WORDBITS * i; } return 0; } #define BITSET_FFS(x) __bitset_ffs(x, ARRAY_SIZE(x)) static inline unsigned __bitset_next_set(unsigned i, BITSET_WORD *tmp, const BITSET_WORD *set, unsigned size) { unsigned bit, word; /* NOTE: The initial conditions for this function are very specific. At * the start of the loop, the tmp variable must be set to *set and the * initial i value set to 0. This way, if there is a bit set in the first * word, we ignore the i-value and just grab that bit (so 0 is ok, even * though 0 may be returned). If the first word is 0, then the value of * `word` will be 0 and we will go on to look at the second word. */ word = BITSET_BITWORD(i); while (*tmp == 0) { word++; if (word >= BITSET_WORDS(size)) return size; *tmp = set[word]; } /* Find the next set bit in the non-zero word */ bit = ffs(*tmp) - 1; /* Unset the bit */ *tmp &= ~(1ull << bit); return word * BITSET_WORDBITS + bit; } #define BITSET_FOREACH_SET(__i, __tmp, __set, __size) \ for (__tmp = *(__set), __i = 0; \ (__i = __bitset_next_set(__i, &__tmp, __set, __size)) < __size;) #ifdef __cplusplus /** * Simple C++ wrapper of a bitset type of static size, with value semantics * and basic bitwise arithmetic operators. The operators defined below are * expected to have the same semantics as the same operator applied to other * fundamental integer types. T is the name of the struct to instantiate * it as, and N is the number of bits in the bitset. */ #define DECLARE_BITSET_T(T, N) struct T { \ EXPLICIT_CONVERSION \ operator bool() const \ { \ for (unsigned i = 0; i < BITSET_WORDS(N); i++) \ if (words[i]) \ return true; \ return false; \ } \ \ T & \ operator=(int x) \ { \ const T c = {{ (BITSET_WORD)x }}; \ return *this = c; \ } \ \ friend bool \ operator==(const T &b, const T &c) \ { \ return BITSET_EQUAL(b.words, c.words); \ } \ \ friend bool \ operator!=(const T &b, const T &c) \ { \ return !(b == c); \ } \ \ friend bool \ operator==(const T &b, int x) \ { \ const T c = {{ (BITSET_WORD)x }}; \ return b == c; \ } \ \ friend bool \ operator!=(const T &b, int x) \ { \ return !(b == x); \ } \ \ friend T \ operator~(const T &b) \ { \ T c; \ for (unsigned i = 0; i < BITSET_WORDS(N); i++) \ c.words[i] = ~b.words[i]; \ return c; \ } \ \ T & \ operator|=(const T &b) \ { \ for (unsigned i = 0; i < BITSET_WORDS(N); i++) \ words[i] |= b.words[i]; \ return *this; \ } \ \ friend T \ operator|(const T &b, const T &c) \ { \ T d = b; \ d |= c; \ return d; \ } \ \ T & \ operator&=(const T &b) \ { \ for (unsigned i = 0; i < BITSET_WORDS(N); i++) \ words[i] &= b.words[i]; \ return *this; \ } \ \ friend T \ operator&(const T &b, const T &c) \ { \ T d = b; \ d &= c; \ return d; \ } \ \ bool \ test(unsigned i) const \ { \ return BITSET_TEST(words, i); \ } \ \ T & \ set(unsigned i) \ { \ BITSET_SET(words, i); \ return *this; \ } \ \ T & \ clear(unsigned i) \ { \ BITSET_CLEAR(words, i); \ return *this; \ } \ \ BITSET_WORD words[BITSET_WORDS(N)]; \ } #endif #endif ================================================ FILE: mesa/src/util/hash_table.c ================================================ /* * Copyright © 2009,2012 Intel Corporation * Copyright © 1988-2004 Keith Packard and Bart Massey. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * Except as contained in this notice, the names of the authors * or their institutions shall not be used in advertising or * otherwise to promote the sale, use or other dealings in this * Software without prior written authorization from the * authors. * * Authors: * Eric Anholt * Keith Packard */ /** * Implements an open-addressing, linear-reprobing hash table. * * For more information, see: * * http://cgit.freedesktop.org/~anholt/hash_table/tree/README */ #include #include #include #include "hash_table.h" #include "ralloc.h" #include "macros.h" #include "main/hash.h" static const uint32_t deleted_key_value; /** * From Knuth -- a good choice for hash/rehash values is p, p-2 where * p and p-2 are both prime. These tables are sized to have an extra 10% * free to avoid exponential performance degradation as the hash table fills */ static const struct { uint32_t max_entries, size, rehash; } hash_sizes[] = { { 2, 5, 3 }, { 4, 7, 5 }, { 8, 13, 11 }, { 16, 19, 17 }, { 32, 43, 41 }, { 64, 73, 71 }, { 128, 151, 149 }, { 256, 283, 281 }, { 512, 571, 569 }, { 1024, 1153, 1151 }, { 2048, 2269, 2267 }, { 4096, 4519, 4517 }, { 8192, 9013, 9011 }, { 16384, 18043, 18041 }, { 32768, 36109, 36107 }, { 65536, 72091, 72089 }, { 131072, 144409, 144407 }, { 262144, 288361, 288359 }, { 524288, 576883, 576881 }, { 1048576, 1153459, 1153457 }, { 2097152, 2307163, 2307161 }, { 4194304, 4613893, 4613891 }, { 8388608, 9227641, 9227639 }, { 16777216, 18455029, 18455027 }, { 33554432, 36911011, 36911009 }, { 67108864, 73819861, 73819859 }, { 134217728, 147639589, 147639587 }, { 268435456, 295279081, 295279079 }, { 536870912, 590559793, 590559791 }, { 1073741824, 1181116273, 1181116271}, { 2147483648ul, 2362232233ul, 2362232231ul} }; static int entry_is_free(const struct hash_table *ht, const struct hash_entry *entry) { return entry->key == ht->freed_key; } static int entry_is_deleted(const struct hash_table *ht, struct hash_entry *entry) { return entry->key == ht->deleted_key; } static int entry_is_present(const struct hash_table *ht, struct hash_entry *entry) { return entry->key != ht->freed_key && entry->key != ht->deleted_key; } bool _mesa_hash_table_init(struct hash_table *ht, void *mem_ctx, uint32_t (*key_hash_function)(const void *key), bool (*key_equals_function)(const void *a, const void *b)) { ht->size_index = 0; ht->size = hash_sizes[ht->size_index].size; ht->rehash = hash_sizes[ht->size_index].rehash; ht->max_entries = hash_sizes[ht->size_index].max_entries; ht->key_hash_function = key_hash_function; ht->key_equals_function = key_equals_function; ht->table = rzalloc_array(mem_ctx, struct hash_entry, ht->size); ht->entries = 0; ht->deleted_entries = 0; ht->deleted_key = &deleted_key_value; ht->freed_key = NULL; return ht->table != NULL; } struct hash_table * _mesa_hash_table_create(void *mem_ctx, uint32_t (*key_hash_function)(const void *key), bool (*key_equals_function)(const void *a, const void *b)) { struct hash_table *ht; /* mem_ctx is used to allocate the hash table, but the hash table is used * to allocate all of the suballocations. */ ht = ralloc(mem_ctx, struct hash_table); if (ht == NULL) return NULL; if (!_mesa_hash_table_init(ht, ht, key_hash_function, key_equals_function)) { ralloc_free(ht); return NULL; } return ht; } struct hash_table * _mesa_hash_table_clone(struct hash_table *src, void *dst_mem_ctx) { struct hash_table *ht; ht = ralloc(dst_mem_ctx, struct hash_table); if (ht == NULL) return NULL; memcpy(ht, src, sizeof(struct hash_table)); ht->table = ralloc_array(ht, struct hash_entry, ht->size); if (ht->table == NULL) { ralloc_free(ht); return NULL; } memcpy(ht->table, src->table, ht->size * sizeof(struct hash_entry)); return ht; } /** * Frees the given hash table. * * If delete_function is passed, it gets called on each entry present before * freeing. */ void _mesa_hash_table_destroy(struct hash_table *ht, void (*delete_function)(struct hash_entry *entry)) { if (!ht) return; if (delete_function) { hash_table_foreach(ht, entry) { delete_function(entry); } } ralloc_free(ht); } /** * Deletes all entries of the given hash table without deleting the table * itself or changing its structure. * * If delete_function is passed, it gets called on each entry present. */ void _mesa_hash_table_clear(struct hash_table *ht, void (*delete_function)(struct hash_entry *entry)) { struct hash_entry *entry; for (entry = ht->table; entry != ht->table + ht->size; entry++) { if (entry->key == ht->freed_key) continue; if (delete_function != NULL && entry->key != ht->deleted_key) delete_function(entry); entry->key = ht->freed_key; } ht->entries = 0; ht->deleted_entries = 0; } /** Sets the value of the key pointer used for deleted entries in the table. * * The assumption is that usually keys are actual pointers, so we use a * default value of a pointer to an arbitrary piece of storage in the library. * But in some cases a consumer wants to store some other sort of value in the * table, like a uint32_t, in which case that pointer may conflict with one of * their valid keys. This lets that user select a safe value. * * This must be called before any keys are actually deleted from the table. */ void _mesa_hash_table_set_deleted_key(struct hash_table *ht, const void *deleted_key) { ht->deleted_key = deleted_key; } void _mesa_hash_table_set_freed_key(struct hash_table *ht, const void *freed_key) { struct hash_entry *entry; if (freed_key == ht->freed_key) return; for (entry = ht->table; entry != ht->table + ht->size; entry++) { if (entry_is_free(ht, entry)) entry->key = freed_key; } ht->freed_key = freed_key; } static struct hash_entry * hash_table_search(struct hash_table *ht, uint32_t hash, const void *key) { uint32_t start_hash_address = hash % ht->size; uint32_t hash_address = start_hash_address; do { uint32_t double_hash; struct hash_entry *entry = ht->table + hash_address; if (entry_is_free(ht, entry)) { return NULL; } else if (entry_is_present(ht, entry) && entry->hash == hash) { if (ht->key_equals_function(key, entry->key)) { return entry; } } double_hash = 1 + hash % ht->rehash; hash_address = (hash_address + double_hash) % ht->size; } while (hash_address != start_hash_address); return NULL; } /** * Finds a hash table entry with the given key and hash of that key. * * Returns NULL if no entry is found. Note that the data pointer may be * modified by the user. */ struct hash_entry * _mesa_hash_table_search(struct hash_table *ht, const void *key) { assert(ht->key_hash_function); return hash_table_search(ht, ht->key_hash_function(key), key); } struct hash_entry * _mesa_hash_table_search_pre_hashed(struct hash_table *ht, uint32_t hash, const void *key) { assert(ht->key_hash_function == NULL || hash == ht->key_hash_function(key)); return hash_table_search(ht, hash, key); } static struct hash_entry * hash_table_insert(struct hash_table *ht, uint32_t hash, const void *key, void *data); static void _mesa_hash_table_rehash(struct hash_table *ht, unsigned new_size_index) { struct hash_table old_ht; struct hash_entry *entry, *table; uint32_t new_size; if (new_size_index >= ARRAY_SIZE(hash_sizes)) return; new_size = hash_sizes[new_size_index].size; table = ralloc_array(ralloc_parent(ht->table), struct hash_entry, new_size); if (table == NULL) return; for (entry = table; entry != table + new_size; entry++) entry->key = ht->freed_key; old_ht = *ht; ht->table = table; ht->size_index = new_size_index; ht->size = new_size; ht->rehash = hash_sizes[ht->size_index].rehash; ht->max_entries = hash_sizes[ht->size_index].max_entries; ht->entries = 0; ht->deleted_entries = 0; hash_table_foreach(&old_ht, entry) { hash_table_insert(ht, entry->hash, entry->key, entry->data); } ralloc_free(old_ht.table); } static struct hash_entry * hash_table_insert(struct hash_table *ht, uint32_t hash, const void *key, void *data) { uint32_t start_hash_address, hash_address; struct hash_entry *available_entry = NULL; assert(key != &ht->freed_key); if (ht->entries >= ht->max_entries) { _mesa_hash_table_rehash(ht, ht->size_index + 1); } else if (ht->deleted_entries + ht->entries >= ht->max_entries) { _mesa_hash_table_rehash(ht, ht->size_index); } start_hash_address = hash % ht->size; hash_address = start_hash_address; do { struct hash_entry *entry = ht->table + hash_address; uint32_t double_hash; if (!entry_is_present(ht, entry)) { /* Stash the first available entry we find */ if (available_entry == NULL) available_entry = entry; if (entry_is_free(ht, entry)) break; } /* Implement replacement when another insert happens * with a matching key. This is a relatively common * feature of hash tables, with the alternative * generally being "insert the new value as well, and * return it first when the key is searched for". * * Note that the hash table doesn't have a delete * callback. If freeing of old data pointers is * required to avoid memory leaks, perform a search * before inserting. */ if (!entry_is_deleted(ht, entry) && entry->hash == hash && ht->key_equals_function(key, entry->key)) { entry->key = key; entry->data = data; return entry; } double_hash = 1 + hash % ht->rehash; hash_address = (hash_address + double_hash) % ht->size; } while (hash_address != start_hash_address); if (available_entry) { if (entry_is_deleted(ht, available_entry)) ht->deleted_entries--; available_entry->hash = hash; available_entry->key = key; available_entry->data = data; ht->entries++; return available_entry; } /* We could hit here if a required resize failed. An unchecked-malloc * application could ignore this result. */ return NULL; } /** * Inserts the key with the given hash into the table. * * Note that insertion may rearrange the table on a resize or rehash, * so previously found hash_entries are no longer valid after this function. */ struct hash_entry * _mesa_hash_table_insert(struct hash_table *ht, const void *key, void *data) { assert(ht->key_hash_function); return hash_table_insert(ht, ht->key_hash_function(key), key, data); } struct hash_entry * _mesa_hash_table_insert_pre_hashed(struct hash_table *ht, uint32_t hash, const void *key, void *data) { assert(ht->key_hash_function == NULL || hash == ht->key_hash_function(key)); return hash_table_insert(ht, hash, key, data); } /** * This function deletes the given hash table entry. * * Note that deletion doesn't otherwise modify the table, so an iteration over * the table deleting entries is safe. */ void _mesa_hash_table_remove(struct hash_table *ht, struct hash_entry *entry) { if (!entry) return; entry->key = ht->deleted_key; ht->entries--; ht->deleted_entries++; } /** * Removes the entry with the corresponding key, if exists. */ void _mesa_hash_table_remove_key(struct hash_table *ht, const void *key) { _mesa_hash_table_remove(ht, _mesa_hash_table_search(ht, key)); } /** * This function is an iterator over the hash table. * * Pass in NULL for the first entry, as in the start of a for loop. Note that * an iteration over the table is O(table_size) not O(entries). */ struct hash_entry * _mesa_hash_table_next_entry(struct hash_table *ht, struct hash_entry *entry) { if (entry == NULL) entry = ht->table; else entry = entry + 1; for (; entry != ht->table + ht->size; entry++) { if (entry_is_present(ht, entry)) { return entry; } } return NULL; } /** * Returns a random entry from the hash table. * * This may be useful in implementing random replacement (as opposed * to just removing everything) in caches based on this hash table * implementation. @predicate may be used to filter entries, or may * be set to NULL for no filtering. */ struct hash_entry * _mesa_hash_table_random_entry(struct hash_table *ht, bool (*predicate)(struct hash_entry *entry)) { struct hash_entry *entry; uint32_t i = rand() % ht->size; if (ht->entries == 0) return NULL; for (entry = ht->table + i; entry != ht->table + ht->size; entry++) { if (entry_is_present(ht, entry) && (!predicate || predicate(entry))) { return entry; } } for (entry = ht->table; entry != ht->table + i; entry++) { if (entry_is_present(ht, entry) && (!predicate || predicate(entry))) { return entry; } } return NULL; } /** * Quick FNV-1a hash implementation based on: * http://www.isthe.com/chongo/tech/comp/fnv/ * * FNV-1a is not be the best hash out there -- Jenkins's lookup3 is supposed * to be quite good, and it probably beats FNV. But FNV has the advantage * that it involves almost no code. For an improvement on both, see Paul * Hsieh's http://www.azillionmonkeys.com/qed/hash.html */ uint32_t _mesa_hash_data(const void *data, size_t size) { return _mesa_fnv32_1a_accumulate_block(_mesa_fnv32_1a_offset_bias, data, size); } /** FNV-1a string hash implementation */ uint32_t _mesa_hash_string(const void *_key) { uint32_t hash = _mesa_fnv32_1a_offset_bias; const char *key = _key; while (*key != 0) { hash = _mesa_fnv32_1a_accumulate(hash, *key); key++; } return hash; } /** * String compare function for use as the comparison callback in * _mesa_hash_table_create(). */ bool _mesa_key_string_equal(const void *a, const void *b) { return strcmp(a, b) == 0; } bool _mesa_key_pointer_equal(const void *a, const void *b) { return a == b; } /** * Helper to create a hash table with pointer keys. */ struct hash_table * _mesa_pointer_hash_table_create(void *mem_ctx) { return _mesa_hash_table_create(mem_ctx, _mesa_hash_pointer, _mesa_key_pointer_equal); } /** * Hash table wrapper which supports 64-bit keys. * * TODO: unify all hash table implementations. */ struct hash_key_u64 { uint64_t value; }; static uint32_t key_u64_hash(const void *key) { return _mesa_hash_data(key, sizeof(struct hash_key_u64)); } static bool key_u64_equals(const void *a, const void *b) { const struct hash_key_u64 *aa = a; const struct hash_key_u64 *bb = b; return aa->value == bb->value; } struct hash_table_u64 * _mesa_hash_table_u64_create(void *mem_ctx) { struct hash_table_u64 *ht; ht = CALLOC_STRUCT(hash_table_u64); if (!ht) return NULL; if (sizeof(void *) == 8) { ht->table = _mesa_hash_table_create(mem_ctx, _mesa_hash_pointer, _mesa_key_pointer_equal); } else { ht->table = _mesa_hash_table_create(mem_ctx, key_u64_hash, key_u64_equals); } if (ht->table) _mesa_hash_table_set_deleted_key(ht->table, uint_key(DELETED_KEY_VALUE)); return ht; } void _mesa_hash_table_u64_destroy(struct hash_table_u64 *ht, void (*delete_function)(struct hash_entry *entry)) { if (!ht) return; if (ht->deleted_key_data) { if (delete_function) { struct hash_table *table = ht->table; struct hash_entry deleted_entry; /* Create a fake entry for the delete function. */ deleted_entry.hash = table->key_hash_function(table->deleted_key); deleted_entry.key = table->deleted_key; deleted_entry.data = ht->deleted_key_data; delete_function(&deleted_entry); } ht->deleted_key_data = NULL; } _mesa_hash_table_destroy(ht->table, delete_function); free(ht); } void _mesa_hash_table_u64_insert(struct hash_table_u64 *ht, uint64_t key, void *data) { if (key == DELETED_KEY_VALUE) { ht->deleted_key_data = data; return; } if (sizeof(void *) == 8) { _mesa_hash_table_insert(ht->table, (void *)(uintptr_t)key, data); } else { struct hash_key_u64 *_key = CALLOC_STRUCT(hash_key_u64); if (!_key) return; _key->value = key; _mesa_hash_table_insert(ht->table, _key, data); } } static struct hash_entry * hash_table_u64_search(struct hash_table_u64 *ht, uint64_t key) { if (sizeof(void *) == 8) { return _mesa_hash_table_search(ht->table, (void *)(uintptr_t)key); } else { struct hash_key_u64 _key = { .value = key }; return _mesa_hash_table_search(ht->table, &_key); } } void * _mesa_hash_table_u64_search(struct hash_table_u64 *ht, uint64_t key) { struct hash_entry *entry; if (key == DELETED_KEY_VALUE) return ht->deleted_key_data; entry = hash_table_u64_search(ht, key); if (!entry) return NULL; return entry->data; } void _mesa_hash_table_u64_remove(struct hash_table_u64 *ht, uint64_t key) { struct hash_entry *entry; if (key == DELETED_KEY_VALUE) { ht->deleted_key_data = NULL; return; } entry = hash_table_u64_search(ht, key); if (!entry) return; if (sizeof(void *) == 8) { _mesa_hash_table_remove(ht->table, entry); } else { struct hash_key *_key = (struct hash_key *)entry->key; _mesa_hash_table_remove(ht->table, entry); free(_key); } } ================================================ FILE: mesa/src/util/hash_table.h ================================================ /* * Copyright © 2009,2012 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * Authors: * Eric Anholt * */ #ifndef _HASH_TABLE_H #define _HASH_TABLE_H #include #include #include #include "c99_compat.h" #include "macros.h" #ifdef __cplusplus extern "C" { #endif struct hash_entry { uint32_t hash; const void *key; void *data; }; struct hash_table { struct hash_entry *table; uint32_t (*key_hash_function)(const void *key); bool (*key_equals_function)(const void *a, const void *b); const void *deleted_key; const void *freed_key; uint32_t size; uint32_t rehash; uint32_t max_entries; uint32_t size_index; uint32_t entries; uint32_t deleted_entries; }; struct hash_table * _mesa_hash_table_create(void *mem_ctx, uint32_t (*key_hash_function)(const void *key), bool (*key_equals_function)(const void *a, const void *b)); bool _mesa_hash_table_init(struct hash_table *ht, void *mem_ctx, uint32_t (*key_hash_function)(const void *key), bool (*key_equals_function)(const void *a, const void *b)); struct hash_table * _mesa_hash_table_clone(struct hash_table *src, void *dst_mem_ctx); void _mesa_hash_table_destroy(struct hash_table *ht, void (*delete_function)(struct hash_entry *entry)); void _mesa_hash_table_clear(struct hash_table *ht, void (*delete_function)(struct hash_entry *entry)); void _mesa_hash_table_set_deleted_key(struct hash_table *ht, const void *deleted_key); void _mesa_hash_table_set_freed_key(struct hash_table *ht, const void *freed_key); static inline uint32_t _mesa_hash_table_num_entries(struct hash_table *ht) { return ht->entries; } struct hash_entry * _mesa_hash_table_insert(struct hash_table *ht, const void *key, void *data); struct hash_entry * _mesa_hash_table_insert_pre_hashed(struct hash_table *ht, uint32_t hash, const void *key, void *data); struct hash_entry * _mesa_hash_table_search(struct hash_table *ht, const void *key); struct hash_entry * _mesa_hash_table_search_pre_hashed(struct hash_table *ht, uint32_t hash, const void *key); void _mesa_hash_table_remove(struct hash_table *ht, struct hash_entry *entry); void _mesa_hash_table_remove_key(struct hash_table *ht, const void *key); struct hash_entry *_mesa_hash_table_next_entry(struct hash_table *ht, struct hash_entry *entry); struct hash_entry * _mesa_hash_table_random_entry(struct hash_table *ht, bool (*predicate)(struct hash_entry *entry)); uint32_t _mesa_hash_data(const void *data, size_t size); uint32_t _mesa_hash_string(const void *key); bool _mesa_key_string_equal(const void *a, const void *b); bool _mesa_key_pointer_equal(const void *a, const void *b); static inline uint32_t _mesa_key_hash_string(const void *key) { return _mesa_hash_string((const char *)key); } static inline uint32_t _mesa_hash_pointer(const void *pointer) { uintptr_t num = (uintptr_t) pointer; return (uint32_t) ((num >> 2) ^ (num >> 6) ^ (num >> 10) ^ (num >> 14)); } struct hash_table * _mesa_pointer_hash_table_create(void *mem_ctx); enum { _mesa_fnv32_1a_offset_bias = 2166136261u, }; static inline uint32_t _mesa_fnv32_1a_accumulate_block(uint32_t hash, const void *data, size_t size) { const uint8_t *bytes = (const uint8_t *)data; while (size-- != 0) { hash ^= *bytes; hash = hash * 0x01000193; bytes++; } return hash; } #define _mesa_fnv32_1a_accumulate(hash, expr) \ _mesa_fnv32_1a_accumulate_block(hash, &(expr), sizeof(expr)) /** * This foreach function is safe against deletion (which just replaces * an entry's data with the deleted marker), but not against insertion * (which may rehash the table, making entry a dangling pointer). */ #define hash_table_foreach(ht, entry) \ for (struct hash_entry *entry = _mesa_hash_table_next_entry(ht, NULL); \ entry != NULL; \ entry = _mesa_hash_table_next_entry(ht, entry)) static inline void hash_table_call_foreach(struct hash_table *ht, void (*callback)(const void *key, void *data, void *closure), void *closure) { hash_table_foreach(ht, entry) callback(entry->key, entry->data, closure); } /** * Hash table wrapper which supports 64-bit keys. */ struct hash_table_u64 { struct hash_table *table; void *deleted_key_data; }; struct hash_table_u64 * _mesa_hash_table_u64_create(void *mem_ctx); void _mesa_hash_table_u64_destroy(struct hash_table_u64 *ht, void (*delete_function)(struct hash_entry *entry)); void _mesa_hash_table_u64_insert(struct hash_table_u64 *ht, uint64_t key, void *data); void * _mesa_hash_table_u64_search(struct hash_table_u64 *ht, uint64_t key); void _mesa_hash_table_u64_remove(struct hash_table_u64 *ht, uint64_t key); #ifdef __cplusplus } /* extern C */ #endif #endif /* _HASH_TABLE_H */ ================================================ FILE: mesa/src/util/list.h ================================================ /************************************************************************** * * Copyright 2006 VMware, Inc., Bismarck, ND. USA. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * **************************************************************************/ /** * \file * List macros heavily inspired by the Linux kernel * list handling. No list looping yet. * * Is not threadsafe, so common operations need to * be protected using an external mutex. */ #ifndef _UTIL_LIST_H_ #define _UTIL_LIST_H_ #include #include #include #include "c99_compat.h" struct list_head { struct list_head *prev; struct list_head *next; }; static inline void list_inithead(struct list_head *item) { item->prev = item; item->next = item; } static inline void list_add(struct list_head *item, struct list_head *list) { item->prev = list; item->next = list->next; list->next->prev = item; list->next = item; } static inline void list_addtail(struct list_head *item, struct list_head *list) { item->next = list; item->prev = list->prev; list->prev->next = item; list->prev = item; } static inline bool list_empty(const struct list_head *list); static inline void list_replace(struct list_head *from, struct list_head *to) { if (list_empty(from)) { list_inithead(to); } else { to->prev = from->prev; to->next = from->next; from->next->prev = to; from->prev->next = to; } } static inline void list_del(struct list_head *item) { item->prev->next = item->next; item->next->prev = item->prev; item->prev = item->next = NULL; } static inline void list_delinit(struct list_head *item) { item->prev->next = item->next; item->next->prev = item->prev; item->next = item; item->prev = item; } static inline bool list_empty(const struct list_head *list) { return list->next == list; } /** * Returns whether the list has exactly one element. */ static inline bool list_is_singular(const struct list_head *list) { return list->next != NULL && list->next != list && list->next->next == list; } static inline unsigned list_length(const struct list_head *list) { struct list_head *node; unsigned length = 0; for (node = list->next; node != list; node = node->next) length++; return length; } static inline void list_splice(struct list_head *src, struct list_head *dst) { if (list_empty(src)) return; src->next->prev = dst; src->prev->next = dst->next; dst->next->prev = src->prev; dst->next = src->next; } static inline void list_splicetail(struct list_head *src, struct list_head *dst) { if (list_empty(src)) return; src->prev->next = dst; src->next->prev = dst->prev; dst->prev->next = src->next; dst->prev = src->prev; } static inline void list_validate(const struct list_head *list) { struct list_head *node; assert(list->next->prev == list && list->prev->next == list); for (node = list->next; node != list; node = node->next) assert(node->next->prev == node && node->prev->next == node); } #define LIST_INITHEAD(__item) list_inithead(__item) #define LIST_ADD(__item, __list) list_add(__item, __list) #define LIST_ADDTAIL(__item, __list) list_addtail(__item, __list) #define LIST_REPLACE(__from, __to) list_replace(__from, __to) #define LIST_DEL(__item) list_del(__item) #define LIST_DELINIT(__item) list_delinit(__item) #define LIST_ENTRY(__type, __item, __field) \ ((__type *)(((char *)(__item)) - offsetof(__type, __field))) #define LIST_IS_EMPTY(__list) \ ((__list)->next == (__list)) /** * Cast from a pointer to a member of a struct back to the containing struct. * * 'sample' MUST be initialized, or else the result is undefined! */ #ifndef container_of #define container_of(ptr, sample, member) \ (void *)((char *)(ptr) \ - ((char *)&(sample)->member - (char *)(sample))) #endif #define list_first_entry(ptr, type, member) \ LIST_ENTRY(type, (ptr)->next, member) #define list_last_entry(ptr, type, member) \ LIST_ENTRY(type, (ptr)->prev, member) #define LIST_FOR_EACH_ENTRY(pos, head, member) \ for (pos = NULL, pos = container_of((head)->next, pos, member); \ &pos->member != (head); \ pos = container_of(pos->member.next, pos, member)) #define LIST_FOR_EACH_ENTRY_SAFE(pos, storage, head, member) \ for (pos = NULL, pos = container_of((head)->next, pos, member), \ storage = container_of(pos->member.next, pos, member); \ &pos->member != (head); \ pos = storage, storage = container_of(storage->member.next, storage, member)) #define LIST_FOR_EACH_ENTRY_SAFE_REV(pos, storage, head, member) \ for (pos = NULL, pos = container_of((head)->prev, pos, member), \ storage = container_of(pos->member.prev, pos, member); \ &pos->member != (head); \ pos = storage, storage = container_of(storage->member.prev, storage, member)) #define LIST_FOR_EACH_ENTRY_FROM(pos, start, head, member) \ for (pos = NULL, pos = container_of((start), pos, member); \ &pos->member != (head); \ pos = container_of(pos->member.next, pos, member)) #define LIST_FOR_EACH_ENTRY_FROM_REV(pos, start, head, member) \ for (pos = NULL, pos = container_of((start), pos, member); \ &pos->member != (head); \ pos = container_of(pos->member.prev, pos, member)) #define list_for_each_entry(type, pos, head, member) \ for (type *pos = LIST_ENTRY(type, (head)->next, member); \ &pos->member != (head); \ pos = LIST_ENTRY(type, pos->member.next, member)) #define list_for_each_entry_safe(type, pos, head, member) \ for (type *pos = LIST_ENTRY(type, (head)->next, member), \ *__next = LIST_ENTRY(type, pos->member.next, member); \ &pos->member != (head); \ pos = __next, \ __next = LIST_ENTRY(type, __next->member.next, member)) #define list_for_each_entry_rev(type, pos, head, member) \ for (type *pos = LIST_ENTRY(type, (head)->prev, member); \ &pos->member != (head); \ pos = LIST_ENTRY(type, pos->member.prev, member)) #define list_for_each_entry_safe_rev(type, pos, head, member) \ for (type *pos = LIST_ENTRY(type, (head)->prev, member), \ *__prev = LIST_ENTRY(type, pos->member.prev, member); \ &pos->member != (head); \ pos = __prev, \ __prev = LIST_ENTRY(type, __prev->member.prev, member)) #define list_for_each_entry_from(type, pos, start, head, member) \ for (type *pos = LIST_ENTRY(type, (start), member); \ &pos->member != (head); \ pos = LIST_ENTRY(type, pos->member.next, member)) #define list_for_each_entry_from_rev(type, pos, start, head, member) \ for (type *pos = LIST_ENTRY(type, (start), member); \ &pos->member != (head); \ pos = LIST_ENTRY(type, pos->member.prev, member)) #endif /*_UTIL_LIST_H_*/ ================================================ FILE: mesa/src/util/macros.h ================================================ /* * Copyright © 2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef UTIL_MACROS_H #define UTIL_MACROS_H #include #include "c99_compat.h" /* Compute the size of an array */ #ifndef ARRAY_SIZE # define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #endif /* For compatibility with Clang's __has_builtin() */ #ifndef __has_builtin # define __has_builtin(x) 0 #endif /** * __builtin_expect macros */ #if !defined(HAVE___BUILTIN_EXPECT) # define __builtin_expect(x, y) (x) #endif #ifndef likely # ifdef HAVE___BUILTIN_EXPECT # define likely(x) __builtin_expect(!!(x), 1) # define unlikely(x) __builtin_expect(!!(x), 0) # else # define likely(x) (x) # define unlikely(x) (x) # endif #endif /** * Static (compile-time) assertion. * Basically, use COND to dimension an array. If COND is false/zero the * array size will be -1 and we'll get a compilation error. */ #define STATIC_ASSERT(COND) \ do { \ (void) sizeof(char [1 - 2*!(COND)]); \ } while (0) /** * Unreachable macro. Useful for suppressing "control reaches end of non-void * function" warnings. */ #ifdef HAVE___BUILTIN_UNREACHABLE #define unreachable(str) \ do { \ assert(!str); \ __builtin_unreachable(); \ } while (0) #elif defined (_MSC_VER) #define unreachable(str) \ do { \ assert(!str); \ __assume(0); \ } while (0) #else #define unreachable(str) assert(!str) #endif /** * Assume macro. Useful for expressing our assumptions to the compiler, * typically for purposes of silencing warnings. */ #if __has_builtin(__builtin_assume) #define assume(expr) \ do { \ assert(expr); \ __builtin_assume(expr); \ } while (0) #elif defined HAVE___BUILTIN_UNREACHABLE #define assume(expr) ((expr) ? ((void) 0) \ : (assert(!"assumption failed"), \ __builtin_unreachable())) #elif defined (_MSC_VER) #define assume(expr) __assume(expr) #else #define assume(expr) assert(expr) #endif /* Attribute const is used for functions that have no effects other than their * return value, and only rely on the argument values to compute the return * value. As a result, calls to it can be CSEed. Note that using memory * pointed to by the arguments is not allowed for const functions. */ #ifdef HAVE_FUNC_ATTRIBUTE_CONST #define ATTRIBUTE_CONST __attribute__((__const__)) #else #define ATTRIBUTE_CONST #endif #ifdef HAVE_FUNC_ATTRIBUTE_FLATTEN #define FLATTEN __attribute__((__flatten__)) #else #define FLATTEN #endif #ifdef HAVE_FUNC_ATTRIBUTE_FORMAT #define PRINTFLIKE(f, a) __attribute__ ((format(__printf__, f, a))) #else #define PRINTFLIKE(f, a) #endif #ifdef HAVE_FUNC_ATTRIBUTE_MALLOC #define MALLOCLIKE __attribute__((__malloc__)) #else #define MALLOCLIKE #endif /* Forced function inlining */ /* Note: Clang also sets __GNUC__ (see other cases below) */ #ifndef ALWAYS_INLINE # if defined(__GNUC__) # define ALWAYS_INLINE inline __attribute__((always_inline)) # elif defined(_MSC_VER) # define ALWAYS_INLINE __forceinline # else # define ALWAYS_INLINE inline # endif #endif /* Used to optionally mark structures with misaligned elements or size as * packed, to trade off performance for space. */ #ifdef HAVE_FUNC_ATTRIBUTE_PACKED #define PACKED __attribute__((__packed__)) #else #define PACKED #endif /* Attribute pure is used for functions that have no effects other than their * return value. As a result, calls to it can be dead code eliminated. */ #ifdef HAVE_FUNC_ATTRIBUTE_PURE #define ATTRIBUTE_PURE __attribute__((__pure__)) #else #define ATTRIBUTE_PURE #endif #ifdef HAVE_FUNC_ATTRIBUTE_RETURNS_NONNULL #define ATTRIBUTE_RETURNS_NONNULL __attribute__((__returns_nonnull__)) #else #define ATTRIBUTE_RETURNS_NONNULL #endif #ifndef NORETURN # ifdef _MSC_VER # define NORETURN __declspec(noreturn) # elif defined HAVE_FUNC_ATTRIBUTE_NORETURN # define NORETURN __attribute__((__noreturn__)) # else # define NORETURN # endif #endif #ifdef __cplusplus /** * Macro function that evaluates to true if T is a trivially * destructible type -- that is, if its (non-virtual) destructor * performs no action and all member variables and base classes are * trivially destructible themselves. */ # if (defined(__clang__) && defined(__has_feature)) # if __has_feature(has_trivial_destructor) # define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T) # endif # elif defined(__GNUC__) # if ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3))) # define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T) # endif # elif defined(_MSC_VER) && !defined(__INTEL_COMPILER) # define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T) # endif # ifndef HAS_TRIVIAL_DESTRUCTOR /* It's always safe (if inefficient) to assume that a * destructor is non-trivial. */ # define HAS_TRIVIAL_DESTRUCTOR(T) (false) # endif #endif /** * PUBLIC/USED macros * * If we build the library with gcc's -fvisibility=hidden flag, we'll * use the PUBLIC macro to mark functions that are to be exported. * * We also need to define a USED attribute, so the optimizer doesn't * inline a static function that we later use in an alias. - ajax */ #ifndef PUBLIC # if defined(__GNUC__) # define PUBLIC __attribute__((visibility("default"))) # define USED __attribute__((used)) # elif defined(_MSC_VER) # define PUBLIC __declspec(dllexport) # define USED # else # define PUBLIC # define USED # endif #endif #ifdef HAVE_FUNC_ATTRIBUTE_UNUSED #define UNUSED __attribute__((unused)) #else #define UNUSED #endif #define MAYBE_UNUSED UNUSED #ifdef HAVE_FUNC_ATTRIBUTE_WARN_UNUSED_RESULT #define MUST_CHECK __attribute__((warn_unused_result)) #else #define MUST_CHECK #endif #if defined(__GNUC__) #define ATTRIBUTE_NOINLINE __attribute__((noinline)) #else #define ATTRIBUTE_NOINLINE #endif /** * Check that STRUCT::FIELD can hold MAXVAL. We use a lot of bitfields * in Mesa/gallium. We have to be sure they're of sufficient size to * hold the largest expected value. * Note that with MSVC, enums are signed and enum bitfields need one extra * high bit (always zero) to ensure the max value is handled correctly. * This macro will detect that with MSVC, but not GCC. */ #define ASSERT_BITFIELD_SIZE(STRUCT, FIELD, MAXVAL) \ do { \ MAYBE_UNUSED STRUCT s; \ s.FIELD = (MAXVAL); \ assert((int) s.FIELD == (MAXVAL) && "Insufficient bitfield size!"); \ } while (0) /** Compute ceiling of integer quotient of A divided by B. */ #define DIV_ROUND_UP( A, B ) ( (A) % (B) == 0 ? (A)/(B) : (A)/(B)+1 ) /** Clamp X to [MIN,MAX]. Turn NaN into MIN, arbitrarily. */ #define CLAMP( X, MIN, MAX ) ( (X)>(MIN) ? ((X)>(MAX) ? (MAX) : (X)) : (MIN) ) /** Minimum of two values: */ #define MIN2( A, B ) ( (A)<(B) ? (A) : (B) ) /** Maximum of two values: */ #define MAX2( A, B ) ( (A)>(B) ? (A) : (B) ) /** Minimum and maximum of three values: */ #define MIN3( A, B, C ) ((A) < (B) ? MIN2(A, C) : MIN2(B, C)) #define MAX3( A, B, C ) ((A) > (B) ? MAX2(A, C) : MAX2(B, C)) /** Align a value to a power of two */ #define ALIGN_POT(x, pot_align) (((x) + (pot_align) - 1) & ~((pot_align) - 1)) /** * Macro for declaring an explicit conversion operator. Defaults to an * implicit conversion if C++11 is not supported. */ #if __cplusplus >= 201103L #define EXPLICIT_CONVERSION explicit #elif defined(__cplusplus) #define EXPLICIT_CONVERSION #endif /** Set a single bit */ #define BITFIELD_BIT(b) (1u << (b)) /** Set all bits up to excluding bit b */ #define BITFIELD_MASK(b) \ ((b) == 32 ? (~0u) : BITFIELD_BIT((b) % 32) - 1) /** Set count bits starting from bit b */ #define BITFIELD_RANGE(b, count) \ (BITFIELD_MASK((b) + (count)) & ~BITFIELD_MASK(b)) /** Set a single bit */ #define BITFIELD64_BIT(b) (1ull << (b)) /** Set all bits up to excluding bit b */ #define BITFIELD64_MASK(b) \ ((b) == 64 ? (~0ull) : BITFIELD64_BIT(b) - 1) /** Set count bits starting from bit b */ #define BITFIELD64_RANGE(b, count) \ (BITFIELD64_MASK((b) + (count)) & ~BITFIELD64_MASK(b)) #endif /* UTIL_MACROS_H */ ================================================ FILE: mesa/src/util/ralloc.c ================================================ /* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include #include #include #include #include #include /* Some versions of MinGW are missing _vscprintf's declaration, although they * still provide the symbol in the import library. */ #ifdef __MINGW32__ _CRTIMP int _vscprintf(const char *format, va_list argptr); #endif #include "ralloc.h" #ifndef va_copy #ifdef __va_copy #define va_copy(dest, src) __va_copy((dest), (src)) #else #define va_copy(dest, src) (dest) = (src) #endif #endif #define CANARY 0x5A1106 /* Align the header's size so that ralloc() allocations will return with the * same alignment as a libc malloc would have (8 on 32-bit GLIBC, 16 on * 64-bit), avoiding performance penalities on x86 and alignment faults on * ARM. */ struct #ifdef _MSC_VER __declspec(align(8)) #elif defined(__LP64__) __attribute__((aligned(16))) #else __attribute__((aligned(8))) #endif ralloc_header { #ifndef NDEBUG /* A canary value used to determine whether a pointer is ralloc'd. */ unsigned canary; #endif struct ralloc_header *parent; /* The first child (head of a linked list) */ struct ralloc_header *child; /* Linked list of siblings */ struct ralloc_header *prev; struct ralloc_header *next; void (*destructor)(void *); }; typedef struct ralloc_header ralloc_header; static void unlink_block(ralloc_header *info); static void unsafe_free(ralloc_header *info); static ralloc_header * get_header(const void *ptr) { ralloc_header *info = (ralloc_header *) (((char *) ptr) - sizeof(ralloc_header)); assert(info->canary == CANARY); return info; } #define PTR_FROM_HEADER(info) (((char *) info) + sizeof(ralloc_header)) static void add_child(ralloc_header *parent, ralloc_header *info) { if (parent != NULL) { info->parent = parent; info->next = parent->child; parent->child = info; if (info->next != NULL) info->next->prev = info; } } void * ralloc_context(const void *ctx) { return ralloc_size(ctx, 0); } void * ralloc_size(const void *ctx, size_t size) { void *block = malloc(size + sizeof(ralloc_header)); ralloc_header *info; ralloc_header *parent; if (unlikely(block == NULL)) return NULL; info = (ralloc_header *) block; /* measurements have shown that calloc is slower (because of * the multiplication overflow checking?), so clear things * manually */ info->parent = NULL; info->child = NULL; info->prev = NULL; info->next = NULL; info->destructor = NULL; parent = ctx != NULL ? get_header(ctx) : NULL; add_child(parent, info); #ifndef NDEBUG info->canary = CANARY; #endif return PTR_FROM_HEADER(info); } void * rzalloc_size(const void *ctx, size_t size) { void *ptr = ralloc_size(ctx, size); if (likely(ptr)) memset(ptr, 0, size); return ptr; } /* helper function - assumes ptr != NULL */ static void * resize(void *ptr, size_t size) { ralloc_header *child, *old, *info; old = get_header(ptr); info = realloc(old, size + sizeof(ralloc_header)); if (info == NULL) return NULL; /* Update parent and sibling's links to the reallocated node. */ if (info != old && info->parent != NULL) { if (info->parent->child == old) info->parent->child = info; if (info->prev != NULL) info->prev->next = info; if (info->next != NULL) info->next->prev = info; } /* Update child->parent links for all children */ for (child = info->child; child != NULL; child = child->next) child->parent = info; return PTR_FROM_HEADER(info); } void * reralloc_size(const void *ctx, void *ptr, size_t size) { if (unlikely(ptr == NULL)) return ralloc_size(ctx, size); assert(ralloc_parent(ptr) == ctx); return resize(ptr, size); } void * ralloc_array_size(const void *ctx, size_t size, unsigned count) { if (count > SIZE_MAX/size) return NULL; return ralloc_size(ctx, size * count); } void * rzalloc_array_size(const void *ctx, size_t size, unsigned count) { if (count > SIZE_MAX/size) return NULL; return rzalloc_size(ctx, size * count); } void * reralloc_array_size(const void *ctx, void *ptr, size_t size, unsigned count) { if (count > SIZE_MAX/size) return NULL; return reralloc_size(ctx, ptr, size * count); } void ralloc_free(void *ptr) { ralloc_header *info; if (ptr == NULL) return; info = get_header(ptr); unlink_block(info); unsafe_free(info); } static void unlink_block(ralloc_header *info) { /* Unlink from parent & siblings */ if (info->parent != NULL) { if (info->parent->child == info) info->parent->child = info->next; if (info->prev != NULL) info->prev->next = info->next; if (info->next != NULL) info->next->prev = info->prev; } info->parent = NULL; info->prev = NULL; info->next = NULL; } static void unsafe_free(ralloc_header *info) { /* Recursively free any children...don't waste time unlinking them. */ ralloc_header *temp; while (info->child != NULL) { temp = info->child; info->child = temp->next; unsafe_free(temp); } /* Free the block itself. Call the destructor first, if any. */ if (info->destructor != NULL) info->destructor(PTR_FROM_HEADER(info)); free(info); } void ralloc_steal(const void *new_ctx, void *ptr) { ralloc_header *info, *parent; if (unlikely(ptr == NULL)) return; info = get_header(ptr); parent = new_ctx ? get_header(new_ctx) : NULL; unlink_block(info); add_child(parent, info); } void ralloc_adopt(const void *new_ctx, void *old_ctx) { ralloc_header *new_info, *old_info, *child; if (unlikely(old_ctx == NULL)) return; old_info = get_header(old_ctx); new_info = get_header(new_ctx); /* If there are no children, bail. */ if (unlikely(old_info->child == NULL)) return; /* Set all the children's parent to new_ctx; get a pointer to the last child. */ for (child = old_info->child; child->next != NULL; child = child->next) { child->parent = new_info; } child->parent = new_info; /* Connect the two lists together; parent them to new_ctx; make old_ctx empty. */ child->next = new_info->child; if (child->next) child->next->prev = child; new_info->child = old_info->child; old_info->child = NULL; } void * ralloc_parent(const void *ptr) { ralloc_header *info; if (unlikely(ptr == NULL)) return NULL; info = get_header(ptr); return info->parent ? PTR_FROM_HEADER(info->parent) : NULL; } void ralloc_set_destructor(const void *ptr, void(*destructor)(void *)) { ralloc_header *info = get_header(ptr); info->destructor = destructor; } char * ralloc_strdup(const void *ctx, const char *str) { size_t n; char *ptr; if (unlikely(str == NULL)) return NULL; n = strlen(str); ptr = ralloc_array(ctx, char, n + 1); memcpy(ptr, str, n); ptr[n] = '\0'; return ptr; } char * ralloc_strndup(const void *ctx, const char *str, size_t max) { size_t n; char *ptr; if (unlikely(str == NULL)) return NULL; n = strnlen(str, max); ptr = ralloc_array(ctx, char, n + 1); memcpy(ptr, str, n); ptr[n] = '\0'; return ptr; } /* helper routine for strcat/strncat - n is the exact amount to copy */ static bool cat(char **dest, const char *str, size_t n) { char *both; size_t existing_length; assert(dest != NULL && *dest != NULL); existing_length = strlen(*dest); both = resize(*dest, existing_length + n + 1); if (unlikely(both == NULL)) return false; memcpy(both + existing_length, str, n); both[existing_length + n] = '\0'; *dest = both; return true; } bool ralloc_strcat(char **dest, const char *str) { return cat(dest, str, strlen(str)); } bool ralloc_strncat(char **dest, const char *str, size_t n) { return cat(dest, str, strnlen(str, n)); } bool ralloc_str_append(char **dest, const char *str, size_t existing_length, size_t str_size) { char *both; assert(dest != NULL && *dest != NULL); both = resize(*dest, existing_length + str_size + 1); if (unlikely(both == NULL)) return false; memcpy(both + existing_length, str, str_size); both[existing_length + str_size] = '\0'; *dest = both; return true; } char * ralloc_asprintf(const void *ctx, const char *fmt, ...) { char *ptr; va_list args; va_start(args, fmt); ptr = ralloc_vasprintf(ctx, fmt, args); va_end(args); return ptr; } /* Return the length of the string that would be generated by a printf-style * format and argument list, not including the \0 byte. */ static size_t printf_length(const char *fmt, va_list untouched_args) { int size; char junk; /* Make a copy of the va_list so the original caller can still use it */ va_list args; va_copy(args, untouched_args); #ifdef _WIN32 /* We need to use _vcsprintf to calculate the size as vsnprintf returns -1 * if the number of characters to write is greater than count. */ size = _vscprintf(fmt, args); (void)junk; #else size = vsnprintf(&junk, 1, fmt, args); #endif assert(size >= 0); va_end(args); return size; } char * ralloc_vasprintf(const void *ctx, const char *fmt, va_list args) { size_t size = printf_length(fmt, args) + 1; char *ptr = ralloc_size(ctx, size); if (ptr != NULL) vsnprintf(ptr, size, fmt, args); return ptr; } bool ralloc_asprintf_append(char **str, const char *fmt, ...) { bool success; va_list args; va_start(args, fmt); success = ralloc_vasprintf_append(str, fmt, args); va_end(args); return success; } bool ralloc_vasprintf_append(char **str, const char *fmt, va_list args) { size_t existing_length; assert(str != NULL); existing_length = *str ? strlen(*str) : 0; return ralloc_vasprintf_rewrite_tail(str, &existing_length, fmt, args); } bool ralloc_asprintf_rewrite_tail(char **str, size_t *start, const char *fmt, ...) { bool success; va_list args; va_start(args, fmt); success = ralloc_vasprintf_rewrite_tail(str, start, fmt, args); va_end(args); return success; } bool ralloc_vasprintf_rewrite_tail(char **str, size_t *start, const char *fmt, va_list args) { size_t new_length; char *ptr; assert(str != NULL); if (unlikely(*str == NULL)) { // Assuming a NULL context is probably bad, but it's expected behavior. *str = ralloc_vasprintf(NULL, fmt, args); *start = strlen(*str); return true; } new_length = printf_length(fmt, args); ptr = resize(*str, *start + new_length + 1); if (unlikely(ptr == NULL)) return false; vsnprintf(ptr + *start, new_length + 1, fmt, args); *str = ptr; *start += new_length; return true; } /*************************************************************************** * Linear allocator for short-lived allocations. *************************************************************************** * * The allocator consists of a parent node (2K buffer), which requires * a ralloc parent, and child nodes (allocations). Child nodes can't be freed * directly, because the parent doesn't track them. You have to release * the parent node in order to release all its children. * * The allocator uses a fixed-sized buffer with a monotonically increasing * offset after each allocation. If the buffer is all used, another buffer * is allocated, sharing the same ralloc parent, so all buffers are at * the same level in the ralloc hierarchy. * * The linear parent node is always the first buffer and keeps track of all * other buffers. */ #define MIN_LINEAR_BUFSIZE 2048 #define SUBALLOC_ALIGNMENT 8 #define LMAGIC 0x87b9c7d3 struct #ifdef _MSC_VER __declspec(align(8)) #elif defined(__LP64__) __attribute__((aligned(16))) #else __attribute__((aligned(8))) #endif linear_header { #ifndef NDEBUG unsigned magic; /* for debugging */ #endif unsigned offset; /* points to the first unused byte in the buffer */ unsigned size; /* size of the buffer */ void *ralloc_parent; /* new buffers will use this */ struct linear_header *next; /* next buffer if we have more */ struct linear_header *latest; /* the only buffer that has free space */ /* After this structure, the buffer begins. * Each suballocation consists of linear_size_chunk as its header followed * by the suballocation, so it goes: * * - linear_size_chunk * - allocated space * - linear_size_chunk * - allocated space * etc. * * linear_size_chunk is only needed by linear_realloc. */ }; struct linear_size_chunk { unsigned size; /* for realloc */ unsigned _padding; }; typedef struct linear_header linear_header; typedef struct linear_size_chunk linear_size_chunk; #define LINEAR_PARENT_TO_HEADER(parent) \ (linear_header*) \ ((char*)(parent) - sizeof(linear_size_chunk) - sizeof(linear_header)) /* Allocate the linear buffer with its header. */ static linear_header * create_linear_node(void *ralloc_ctx, unsigned min_size) { linear_header *node; min_size += sizeof(linear_size_chunk); if (likely(min_size < MIN_LINEAR_BUFSIZE)) min_size = MIN_LINEAR_BUFSIZE; node = ralloc_size(ralloc_ctx, sizeof(linear_header) + min_size); if (unlikely(!node)) return NULL; #ifndef NDEBUG node->magic = LMAGIC; #endif node->offset = 0; node->size = min_size; node->ralloc_parent = ralloc_ctx; node->next = NULL; node->latest = node; return node; } void * linear_alloc_child(void *parent, unsigned size) { linear_header *first = LINEAR_PARENT_TO_HEADER(parent); linear_header *latest = first->latest; linear_header *new_node; linear_size_chunk *ptr; unsigned full_size; assert(first->magic == LMAGIC); assert(!latest->next); size = ALIGN_POT(size, SUBALLOC_ALIGNMENT); full_size = sizeof(linear_size_chunk) + size; if (unlikely(latest->offset + full_size > latest->size)) { /* allocate a new node */ new_node = create_linear_node(latest->ralloc_parent, size); if (unlikely(!new_node)) return NULL; first->latest = new_node; latest->latest = new_node; latest->next = new_node; latest = new_node; } ptr = (linear_size_chunk *)((char*)&latest[1] + latest->offset); ptr->size = size; latest->offset += full_size; assert((uintptr_t)&ptr[1] % SUBALLOC_ALIGNMENT == 0); return &ptr[1]; } void * linear_alloc_parent(void *ralloc_ctx, unsigned size) { linear_header *node; if (unlikely(!ralloc_ctx)) return NULL; size = ALIGN_POT(size, SUBALLOC_ALIGNMENT); node = create_linear_node(ralloc_ctx, size); if (unlikely(!node)) return NULL; return linear_alloc_child((char*)node + sizeof(linear_header) + sizeof(linear_size_chunk), size); } void * linear_zalloc_child(void *parent, unsigned size) { void *ptr = linear_alloc_child(parent, size); if (likely(ptr)) memset(ptr, 0, size); return ptr; } void * linear_zalloc_parent(void *parent, unsigned size) { void *ptr = linear_alloc_parent(parent, size); if (likely(ptr)) memset(ptr, 0, size); return ptr; } void linear_free_parent(void *ptr) { linear_header *node; if (unlikely(!ptr)) return; node = LINEAR_PARENT_TO_HEADER(ptr); assert(node->magic == LMAGIC); while (node) { void *ptr = node; node = node->next; ralloc_free(ptr); } } void ralloc_steal_linear_parent(void *new_ralloc_ctx, void *ptr) { linear_header *node; if (unlikely(!ptr)) return; node = LINEAR_PARENT_TO_HEADER(ptr); assert(node->magic == LMAGIC); while (node) { ralloc_steal(new_ralloc_ctx, node); node->ralloc_parent = new_ralloc_ctx; node = node->next; } } void * ralloc_parent_of_linear_parent(void *ptr) { linear_header *node = LINEAR_PARENT_TO_HEADER(ptr); assert(node->magic == LMAGIC); return node->ralloc_parent; } void * linear_realloc(void *parent, void *old, unsigned new_size) { unsigned old_size = 0; ralloc_header *new_ptr; new_ptr = linear_alloc_child(parent, new_size); if (unlikely(!old)) return new_ptr; old_size = ((linear_size_chunk*)old)[-1].size; if (likely(new_ptr && old_size)) memcpy(new_ptr, old, MIN2(old_size, new_size)); return new_ptr; } /* All code below is pretty much copied from ralloc and only the alloc * calls are different. */ char * linear_strdup(void *parent, const char *str) { unsigned n; char *ptr; if (unlikely(!str)) return NULL; n = strlen(str); ptr = linear_alloc_child(parent, n + 1); if (unlikely(!ptr)) return NULL; memcpy(ptr, str, n); ptr[n] = '\0'; return ptr; } char * linear_asprintf(void *parent, const char *fmt, ...) { char *ptr; va_list args; va_start(args, fmt); ptr = linear_vasprintf(parent, fmt, args); va_end(args); return ptr; } char * linear_vasprintf(void *parent, const char *fmt, va_list args) { unsigned size = printf_length(fmt, args) + 1; char *ptr = linear_alloc_child(parent, size); if (ptr != NULL) vsnprintf(ptr, size, fmt, args); return ptr; } bool linear_asprintf_append(void *parent, char **str, const char *fmt, ...) { bool success; va_list args; va_start(args, fmt); success = linear_vasprintf_append(parent, str, fmt, args); va_end(args); return success; } bool linear_vasprintf_append(void *parent, char **str, const char *fmt, va_list args) { size_t existing_length; assert(str != NULL); existing_length = *str ? strlen(*str) : 0; return linear_vasprintf_rewrite_tail(parent, str, &existing_length, fmt, args); } bool linear_asprintf_rewrite_tail(void *parent, char **str, size_t *start, const char *fmt, ...) { bool success; va_list args; va_start(args, fmt); success = linear_vasprintf_rewrite_tail(parent, str, start, fmt, args); va_end(args); return success; } bool linear_vasprintf_rewrite_tail(void *parent, char **str, size_t *start, const char *fmt, va_list args) { size_t new_length; char *ptr; assert(str != NULL); if (unlikely(*str == NULL)) { *str = linear_vasprintf(parent, fmt, args); *start = strlen(*str); return true; } new_length = printf_length(fmt, args); ptr = linear_realloc(parent, *str, *start + new_length + 1); if (unlikely(ptr == NULL)) return false; vsnprintf(ptr + *start, new_length + 1, fmt, args); *str = ptr; *start += new_length; return true; } /* helper routine for strcat/strncat - n is the exact amount to copy */ static bool linear_cat(void *parent, char **dest, const char *str, unsigned n) { char *both; unsigned existing_length; assert(dest != NULL && *dest != NULL); existing_length = strlen(*dest); both = linear_realloc(parent, *dest, existing_length + n + 1); if (unlikely(both == NULL)) return false; memcpy(both + existing_length, str, n); both[existing_length + n] = '\0'; *dest = both; return true; } bool linear_strcat(void *parent, char **dest, const char *str) { return linear_cat(parent, dest, str, strlen(str)); } ================================================ FILE: mesa/src/util/ralloc.h ================================================ /* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file ralloc.h * * ralloc: a recursive memory allocator * * The ralloc memory allocator creates a hierarchy of allocated * objects. Every allocation is in reference to some parent, and * every allocated object can in turn be used as the parent of a * subsequent allocation. This allows for extremely convenient * discarding of an entire tree/sub-tree of allocations by calling * ralloc_free on any particular object to free it and all of its * children. * * The conceptual working of ralloc was directly inspired by Andrew * Tridgell's talloc, but ralloc is an independent implementation * released under the MIT license and tuned for Mesa. * * talloc is more sophisticated than ralloc in that it includes reference * counting and useful debugging features. However, it is released under * a non-permissive open source license. */ #ifndef RALLOC_H #define RALLOC_H #include #include #include #include "macros.h" #ifdef __cplusplus extern "C" { #endif /** * \def ralloc(ctx, type) * Allocate a new object chained off of the given context. * * This is equivalent to: * \code * ((type *) ralloc_size(ctx, sizeof(type)) * \endcode */ #define ralloc(ctx, type) ((type *) ralloc_size(ctx, sizeof(type))) /** * \def rzalloc(ctx, type) * Allocate a new object out of the given context and initialize it to zero. * * This is equivalent to: * \code * ((type *) rzalloc_size(ctx, sizeof(type)) * \endcode */ #define rzalloc(ctx, type) ((type *) rzalloc_size(ctx, sizeof(type))) /** * Allocate a new ralloc context. * * While any ralloc'd pointer can be used as a context, sometimes it is useful * to simply allocate a context with no associated memory. * * It is equivalent to: * \code * ((type *) ralloc_size(ctx, 0) * \endcode */ void *ralloc_context(const void *ctx); /** * Allocate memory chained off of the given context. * * This is the core allocation routine which is used by all others. It * simply allocates storage for \p size bytes and returns the pointer, * similar to \c malloc. */ void *ralloc_size(const void *ctx, size_t size) MALLOCLIKE; /** * Allocate zero-initialized memory chained off of the given context. * * This is similar to \c calloc with a size of 1. */ void *rzalloc_size(const void *ctx, size_t size) MALLOCLIKE; /** * Resize a piece of ralloc-managed memory, preserving data. * * Similar to \c realloc. Unlike C89, passing 0 for \p size does not free the * memory. Instead, it resizes it to a 0-byte ralloc context, just like * calling ralloc_size(ctx, 0). This is different from talloc. * * \param ctx The context to use for new allocation. If \p ptr != NULL, * it must be the same as ralloc_parent(\p ptr). * \param ptr Pointer to the memory to be resized. May be NULL. * \param size The amount of memory to allocate, in bytes. */ void *reralloc_size(const void *ctx, void *ptr, size_t size); /// \defgroup array Array Allocators @{ /** * \def ralloc_array(ctx, type, count) * Allocate an array of objects chained off the given context. * * Similar to \c calloc, but does not initialize the memory to zero. * * More than a convenience function, this also checks for integer overflow when * multiplying \c sizeof(type) and \p count. This is necessary for security. * * This is equivalent to: * \code * ((type *) ralloc_array_size(ctx, sizeof(type), count) * \endcode */ #define ralloc_array(ctx, type, count) \ ((type *) ralloc_array_size(ctx, sizeof(type), count)) /** * \def rzalloc_array(ctx, type, count) * Allocate a zero-initialized array chained off the given context. * * Similar to \c calloc. * * More than a convenience function, this also checks for integer overflow when * multiplying \c sizeof(type) and \p count. This is necessary for security. * * This is equivalent to: * \code * ((type *) rzalloc_array_size(ctx, sizeof(type), count) * \endcode */ #define rzalloc_array(ctx, type, count) \ ((type *) rzalloc_array_size(ctx, sizeof(type), count)) /** * \def reralloc(ctx, ptr, type, count) * Resize a ralloc-managed array, preserving data. * * Similar to \c realloc. Unlike C89, passing 0 for \p size does not free the * memory. Instead, it resizes it to a 0-byte ralloc context, just like * calling ralloc_size(ctx, 0). This is different from talloc. * * More than a convenience function, this also checks for integer overflow when * multiplying \c sizeof(type) and \p count. This is necessary for security. * * \param ctx The context to use for new allocation. If \p ptr != NULL, * it must be the same as ralloc_parent(\p ptr). * \param ptr Pointer to the array to be resized. May be NULL. * \param type The element type. * \param count The number of elements to allocate. */ #define reralloc(ctx, ptr, type, count) \ ((type *) reralloc_array_size(ctx, ptr, sizeof(type), count)) /** * Allocate memory for an array chained off the given context. * * Similar to \c calloc, but does not initialize the memory to zero. * * More than a convenience function, this also checks for integer overflow when * multiplying \p size and \p count. This is necessary for security. */ void *ralloc_array_size(const void *ctx, size_t size, unsigned count) MALLOCLIKE; /** * Allocate a zero-initialized array chained off the given context. * * Similar to \c calloc. * * More than a convenience function, this also checks for integer overflow when * multiplying \p size and \p count. This is necessary for security. */ void *rzalloc_array_size(const void *ctx, size_t size, unsigned count) MALLOCLIKE; /** * Resize a ralloc-managed array, preserving data. * * Similar to \c realloc. Unlike C89, passing 0 for \p size does not free the * memory. Instead, it resizes it to a 0-byte ralloc context, just like * calling ralloc_size(ctx, 0). This is different from talloc. * * More than a convenience function, this also checks for integer overflow when * multiplying \c sizeof(type) and \p count. This is necessary for security. * * \param ctx The context to use for new allocation. If \p ptr != NULL, * it must be the same as ralloc_parent(\p ptr). * \param ptr Pointer to the array to be resized. May be NULL. * \param size The size of an individual element. * \param count The number of elements to allocate. * * \return True unless allocation failed. */ void *reralloc_array_size(const void *ctx, void *ptr, size_t size, unsigned count); /// @} /** * Free a piece of ralloc-managed memory. * * This will also free the memory of any children allocated this context. */ void ralloc_free(void *ptr); /** * "Steal" memory from one context, changing it to another. * * This changes \p ptr's context to \p new_ctx. This is quite useful if * memory is allocated out of a temporary context. */ void ralloc_steal(const void *new_ctx, void *ptr); /** * Reparent all children from one context to another. * * This effectively calls ralloc_steal(new_ctx, child) for all children of \p old_ctx. */ void ralloc_adopt(const void *new_ctx, void *old_ctx); /** * Return the given pointer's ralloc context. */ void *ralloc_parent(const void *ptr); /** * Set a callback to occur just before an object is freed. */ void ralloc_set_destructor(const void *ptr, void(*destructor)(void *)); /// \defgroup array String Functions @{ /** * Duplicate a string, allocating the memory from the given context. */ char *ralloc_strdup(const void *ctx, const char *str) MALLOCLIKE; /** * Duplicate a string, allocating the memory from the given context. * * Like \c strndup, at most \p n characters are copied. If \p str is longer * than \p n characters, \p n are copied, and a termining \c '\0' byte is added. */ char *ralloc_strndup(const void *ctx, const char *str, size_t n) MALLOCLIKE; /** * Concatenate two strings, allocating the necessary space. * * This appends \p str to \p *dest, similar to \c strcat, using ralloc_resize * to expand \p *dest to the appropriate size. \p dest will be updated to the * new pointer unless allocation fails. * * The result will always be null-terminated. * * \return True unless allocation failed. */ bool ralloc_strcat(char **dest, const char *str); /** * Concatenate two strings, allocating the necessary space. * * This appends at most \p n bytes of \p str to \p *dest, using ralloc_resize * to expand \p *dest to the appropriate size. \p dest will be updated to the * new pointer unless allocation fails. * * The result will always be null-terminated; \p str does not need to be null * terminated if it is longer than \p n. * * \return True unless allocation failed. */ bool ralloc_strncat(char **dest, const char *str, size_t n); /** * Concatenate two strings, allocating the necessary space. * * This appends \p n bytes of \p str to \p *dest, using ralloc_resize * to expand \p *dest to the appropriate size. \p dest will be updated to the * new pointer unless allocation fails. * * The result will always be null-terminated. * * This function differs from ralloc_strcat() and ralloc_strncat() in that it * does not do any strlen() calls which can become costly on large strings. * * \return True unless allocation failed. */ bool ralloc_str_append(char **dest, const char *str, size_t existing_length, size_t str_size); /** * Print to a string. * * This is analogous to \c sprintf, but allocates enough space (using \p ctx * as the context) for the resulting string. * * \return The newly allocated string. */ char *ralloc_asprintf (const void *ctx, const char *fmt, ...) PRINTFLIKE(2, 3) MALLOCLIKE; /** * Print to a string, given a va_list. * * This is analogous to \c vsprintf, but allocates enough space (using \p ctx * as the context) for the resulting string. * * \return The newly allocated string. */ char *ralloc_vasprintf(const void *ctx, const char *fmt, va_list args) MALLOCLIKE; /** * Rewrite the tail of an existing string, starting at a given index. * * Overwrites the contents of *str starting at \p start with newly formatted * text, including a new null-terminator. Allocates more memory as necessary. * * This can be used to append formatted text when the length of the existing * string is already known, saving a strlen() call. * * \sa ralloc_asprintf_append * * \param str The string to be updated. * \param start The index to start appending new data at. * \param fmt A printf-style formatting string * * \p str will be updated to the new pointer unless allocation fails. * \p start will be increased by the length of the newly formatted text. * * \return True unless allocation failed. */ bool ralloc_asprintf_rewrite_tail(char **str, size_t *start, const char *fmt, ...) PRINTFLIKE(3, 4); /** * Rewrite the tail of an existing string, starting at a given index. * * Overwrites the contents of *str starting at \p start with newly formatted * text, including a new null-terminator. Allocates more memory as necessary. * * This can be used to append formatted text when the length of the existing * string is already known, saving a strlen() call. * * \sa ralloc_vasprintf_append * * \param str The string to be updated. * \param start The index to start appending new data at. * \param fmt A printf-style formatting string * \param args A va_list containing the data to be formatted * * \p str will be updated to the new pointer unless allocation fails. * \p start will be increased by the length of the newly formatted text. * * \return True unless allocation failed. */ bool ralloc_vasprintf_rewrite_tail(char **str, size_t *start, const char *fmt, va_list args); /** * Append formatted text to the supplied string. * * This is equivalent to * \code * ralloc_asprintf_rewrite_tail(str, strlen(*str), fmt, ...) * \endcode * * \sa ralloc_asprintf * \sa ralloc_asprintf_rewrite_tail * \sa ralloc_strcat * * \p str will be updated to the new pointer unless allocation fails. * * \return True unless allocation failed. */ bool ralloc_asprintf_append (char **str, const char *fmt, ...) PRINTFLIKE(2, 3); /** * Append formatted text to the supplied string, given a va_list. * * This is equivalent to * \code * ralloc_vasprintf_rewrite_tail(str, strlen(*str), fmt, args) * \endcode * * \sa ralloc_vasprintf * \sa ralloc_vasprintf_rewrite_tail * \sa ralloc_strcat * * \p str will be updated to the new pointer unless allocation fails. * * \return True unless allocation failed. */ bool ralloc_vasprintf_append(char **str, const char *fmt, va_list args); /// @} /** * Declare C++ new and delete operators which use ralloc. * * Placing this macro in the body of a class makes it possible to do: * * TYPE *var = new(mem_ctx) TYPE(...); * delete var; * * which is more idiomatic in C++ than calling ralloc. */ #define DECLARE_ALLOC_CXX_OPERATORS_TEMPLATE(TYPE, ALLOC_FUNC) \ private: \ static void _ralloc_destructor(void *p) \ { \ reinterpret_cast(p)->TYPE::~TYPE(); \ } \ public: \ static void* operator new(size_t size, void *mem_ctx) \ { \ void *p = ALLOC_FUNC(mem_ctx, size); \ assert(p != NULL); \ if (!HAS_TRIVIAL_DESTRUCTOR(TYPE)) \ ralloc_set_destructor(p, _ralloc_destructor); \ return p; \ } \ \ static void operator delete(void *p) \ { \ /* The object's destructor is guaranteed to have already been \ * called by the delete operator at this point -- Make sure it's \ * not called again. \ */ \ if (!HAS_TRIVIAL_DESTRUCTOR(TYPE)) \ ralloc_set_destructor(p, NULL); \ ralloc_free(p); \ } #define DECLARE_RALLOC_CXX_OPERATORS(type) \ DECLARE_ALLOC_CXX_OPERATORS_TEMPLATE(type, ralloc_size) #define DECLARE_RZALLOC_CXX_OPERATORS(type) \ DECLARE_ALLOC_CXX_OPERATORS_TEMPLATE(type, rzalloc_size) #define DECLARE_LINEAR_ALLOC_CXX_OPERATORS(type) \ DECLARE_ALLOC_CXX_OPERATORS_TEMPLATE(type, linear_alloc_child) #define DECLARE_LINEAR_ZALLOC_CXX_OPERATORS(type) \ DECLARE_ALLOC_CXX_OPERATORS_TEMPLATE(type, linear_zalloc_child) /** * Do a fast allocation from the linear buffer, also known as the child node * from the allocator's point of view. It can't be freed directly. You have * to free the parent or the ralloc parent. * * \param parent parent node of the linear allocator * \param size size to allocate (max 32 bits) */ void *linear_alloc_child(void *parent, unsigned size); /** * Allocate a parent node that will hold linear buffers. The returned * allocation is actually the first child node, but it's also the handle * of the parent node. Use it for all child node allocations. * * \param ralloc_ctx ralloc context, must not be NULL * \param size size to allocate (max 32 bits) */ void *linear_alloc_parent(void *ralloc_ctx, unsigned size); /** * Same as linear_alloc_child, but also clears memory. */ void *linear_zalloc_child(void *parent, unsigned size); /** * Same as linear_alloc_parent, but also clears memory. */ void *linear_zalloc_parent(void *ralloc_ctx, unsigned size); /** * Free the linear parent node. This will free all child nodes too. * Freeing the ralloc parent will also free this. */ void linear_free_parent(void *ptr); /** * Same as ralloc_steal, but steals the linear parent node. */ void ralloc_steal_linear_parent(void *new_ralloc_ctx, void *ptr); /** * Return the ralloc parent of the linear parent node. */ void *ralloc_parent_of_linear_parent(void *ptr); /** * Same as realloc except that the linear allocator doesn't free child nodes, * so it's reduced to memory duplication. It's used in places where * reallocation is required. Don't use it often. It's much slower than * realloc. */ void *linear_realloc(void *parent, void *old, unsigned new_size); /* The functions below have the same semantics as their ralloc counterparts, * except that they always allocate a linear child node. */ char *linear_strdup(void *parent, const char *str); char *linear_asprintf(void *parent, const char *fmt, ...); char *linear_vasprintf(void *parent, const char *fmt, va_list args); bool linear_asprintf_append(void *parent, char **str, const char *fmt, ...); bool linear_vasprintf_append(void *parent, char **str, const char *fmt, va_list args); bool linear_asprintf_rewrite_tail(void *parent, char **str, size_t *start, const char *fmt, ...); bool linear_vasprintf_rewrite_tail(void *parent, char **str, size_t *start, const char *fmt, va_list args); bool linear_strcat(void *parent, char **dest, const char *str); #ifdef __cplusplus } /* end of extern "C" */ #endif #endif ================================================ FILE: meson.build ================================================ project('GPUTop', 'c', 'cpp', version : '0.0.2', default_options : [ 'warning_level=2', 'c_std=gnu99', 'default_library=static', ], license : 'MIT', meson_version : '>= 0.44.0') add_project_arguments(['-Wno-unused-parameter', '-Wno-sign-compare'], language: ['c', 'cpp']) protobuf_c_dep = subproject('protobuf-c').get_variable('protobuf_c_dep') c = meson.get_compiler('c') cc = meson.get_compiler('cpp') prog_python2 = find_program('python2') build_native_ui = get_option('native_ui') build_webui = get_option('webui') if build_webui and build_native_ui error('Cannot build webui and native tools in the same build') endif if meson.is_cross_build() protoc_c = subproject('protobuf-c').get_variable('protoc_c_native') leg = subproject('peg').get_variable('leg_native') else protoc_c = subproject('protobuf-c').get_variable('protoc_c') leg = subproject('peg').get_variable('leg') endif subdir('mesa') subdir('lib') if not build_webui libuv_dep = subproject('libuv').get_variable('libuv_dep') wslay_dep = subproject('wslay').get_variable('wslay_dep') h2o_dep = subproject('h2o').get_variable('h2o_dep') subdir('server') subdir('wrapper') subdir('utils') endif subdir('ui') ================================================ FILE: meson_options.txt ================================================ option('webui', type : 'boolean', value : 'false') option('native_ui', type : 'boolean', value : 'false') option('native_ui_gtk', type : 'boolean', value : 'false') ================================================ FILE: scripts/deploy-demo-site.sh ================================================ #!/bin/bash mkdir deploy cd deploy git config --global user.email "Travis@travis.org" git config --global user.name "Travis CI" git clone --quiet https://${GH_TOKEN}@github.com/gputop/gputop.github.io.git &> /dev/null cd gputop.github.io rm -rf * cp ${TRAVIS_BUILD_DIR}/travis-build/ui/*.js ${TRAVIS_BUILD_DIR}/travis-build/ui/*.wasm . if [ -d ${TRAVIS_BUILD_DIR}/travis-build/ui/gputop-ui.wasm.map ]; then cp ${TRAVIS_BUILD_DIR}/travis-build/ui/gputop-ui.wasm.map . fi if [ -d ${TRAVIS_BUILD_DIR}/travis-build/ui/gputop-ui.wast ]; then cp ${TRAVIS_BUILD_DIR}/travis-build/ui/gputop-ui.wast . fi cp ${TRAVIS_BUILD_DIR}/ui/*.html ${TRAVIS_BUILD_DIR}/ui/*.css ${TRAVIS_BUILD_DIR}/ui/favicon.ico . echo "disable jekyll">.nojekyll echo "www.gputop.com" >> CNAME git add --all git status git commit -m "Deployed by Travis" git push origin master &> /dev/null ================================================ FILE: scripts/gen-template.py ================================================ #!/usr/bin/env python2 # # Copyright (c) 2017 Intel Corporation # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice (including the next # paragraph) shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import argparse import textwrap from mako.template import Template def main(): parser = argparse.ArgumentParser() parser.add_argument('--template', help='Template to use.', required=True) parser.add_argument('--out', help='Where to write the output file.', required=True) parser.add_argument('files', help='Files to include in the templating', metavar='F', nargs='+') args = parser.parse_args() template = Template(textwrap.dedent(open(args.template).read()), output_encoding='utf-8') with open(args.out, 'wb') as f: f.write(template.render(files=args.files)) if __name__ == '__main__': main() ================================================ FILE: scripts/gputop-oa-codegen.py ================================================ #!/usr/bin/env python2 # # Copyright (c) 2015-2018 Intel Corporation # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice (including the next # paragraph) shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import argparse import os import sys import textwrap import xml.etree.cElementTree as et import pylibs.codegen as codegen h = None c = None hashed_funcs = {} xml_equations = None def check_operand_type(set, arg): if arg.isdigit(): return "\n" + arg + "" elif arg[0] == "$": if arg in set.counter_vars: description = set.counter_vars[arg].get('description') elif arg in hw_vars and 'desc' in hw_vars[arg]: description = hw_vars[arg]['desc']; else: description = None if description != None: return "\n\n" + arg + "\n" + description + "\n" else: return "" + arg + "" return arg # http://en.cppreference.com/w/c/language/operator_precedence and_precedence = 8 shft_precedence = 5 mul_precedence = 3 add_precedence = 2 sub_precedence = 2 default_precedence = 16 #a high value which denotes no brackets needed def put_brackets(arg): return "\n(" + arg + "\n)" def mathml_splice_add(set, args): operand_0 = check_operand_type(set, args[0][0]) operand_1 = check_operand_type(set, args[1][0]) if args[0][1] < add_precedence: operand_0 = put_brackets(args[0][0]) if args[1][1] < add_precedence: operand_1 = put_brackets(args[1][0]) return [operand_1 + "\n+" + operand_0, add_precedence] def mathml_splice_div(set, args): operand_0 = check_operand_type(set, args[0][0]) operand_1 = check_operand_type(set, args[1][0]) return ["\n\n" + operand_1 + "\n\n" + operand_0 + "\n", default_precedence] def mathml_splice_max(set, args): operand_0 = check_operand_type(set, args[0][0]) operand_1 = check_operand_type(set, args[1][0]) return ["\nmax ( " + operand_1 + "\n , " + operand_0 + "\n ) ", default_precedence] def mathml_splice_mul(set, args): operand_0 = check_operand_type(set, args[0][0]) operand_1 = check_operand_type(set, args[1][0]) if args[0][1] < mul_precedence: operand_0 = put_brackets(args[0][0]) if args[1][1] < mul_precedence: operand_1 = put_brackets(args[1][0]) return [operand_1 + "\n*" + operand_0, mul_precedence] def mathml_splice_sub(set, args): operand_0 = check_operand_type(set, args[0][0]) operand_1 = check_operand_type(set, args[1][0]) if args[0][1] < sub_precedence: operand_0 = put_brackets(args[0][0]) if args[1][1] < sub_precedence: operand_1 = put_brackets(args[1][0]) return [operand_1 + "\n-" + operand_0, sub_precedence] def mathml_splice_read(set, args): return ["\n\n" + args[1][0] + args[0][0] + "\nplaceholder\n", default_precedence] def mathml_splice_read_reg(set, args): return ["\n\n" + args[0][0] + "\nplaceholder\n", default_precedence] def mathml_splice_min(set, args): operand_0 = check_operand_type(set, args[0][0]) operand_1 = check_operand_type(set, args[1][0]) return ["\nmin ( " + operand_1 + "\n , " + operand_0 + "\n ) ", default_precedence] def mathml_splice_lshft(set, args): operand_0 = check_operand_type(set, args[0][0]) operand_1 = check_operand_type(set, args[1][0]) if args[0][1] < shft_precedence: operand_0 = put_brackets(args[0][0]) if args[1][1] < shft_precedence: operand_1 = put_brackets(args[1][0]) return [operand_1 + "\n<<" + operand_0, shft_precedence] def mathml_splice_rshft(set, args): operand_0 = check_operand_type(set, args[0][0]) operand_1 = check_operand_type(set, args[1][0]) if args[0][1] < mul_precedence: operand_0 = put_brackets(args[0][0]) if args[1][1] < mul_precedence: operand_1 = put_brackets(args[1][0]) return [operand_1 + "\n>>" + operand_0, mul_precedence] def mathml_splice_and(set, args): operand_0 = check_operand_type(set, args[0][0]) operand_1 = check_operand_type(set, args[1][0]) if args[0][1] < and_precedence: operand_0 = put_brackets(args[0][0]) if args[1][1] < and_precedence: operand_1 = put_brackets(args[1][0]) return [operand_1 + "\n&" + operand_0, and_precedence] def emit_fadd(tmp_id, args): c("double tmp{0} = {1} + {2};".format(tmp_id, args[1], args[0])) return tmp_id + 1 # Be careful to check for divide by zero... def emit_fdiv(tmp_id, args): c("double tmp{0} = {1};".format(tmp_id, args[1])) c("double tmp{0} = {1};".format(tmp_id + 1, args[0])) c("double tmp{0} = tmp{1} ? tmp{2} / tmp{1} : 0;".format(tmp_id + 2, tmp_id + 1, tmp_id)) return tmp_id + 3 def emit_fmax(tmp_id, args): c("double tmp{0} = {1};".format(tmp_id, args[1])) c("double tmp{0} = {1};".format(tmp_id + 1, args[0])) c("double tmp{0} = MAX(tmp{1}, tmp{2});".format(tmp_id + 2, tmp_id, tmp_id + 1)) return tmp_id + 3 def emit_fmul(tmp_id, args): c("double tmp{0} = {1} * {2};".format(tmp_id, args[1], args[0])) return tmp_id + 1 def emit_fsub(tmp_id, args): c("double tmp{0} = {1} - {2};".format(tmp_id, args[1], args[0])) return tmp_id + 1 def emit_read(tmp_id, args): type = args[1].lower() c("uint64_t tmp{0} = accumulator[metric_set->{1}_offset + {2}];".format(tmp_id, type, args[0])) return tmp_id + 1 def emit_read_reg(tmp_id, args): c("uint64_t tmp{0} = 0;".format(tmp_id)) return tmp_id + 1 def emit_uadd(tmp_id, args): c("uint64_t tmp{0} = {1} + {2};".format(tmp_id, args[1], args[0])) return tmp_id + 1 # Be careful to check for divide by zero... def emit_udiv(tmp_id, args): c("uint64_t tmp{0} = {1};".format(tmp_id, args[1])) c("uint64_t tmp{0} = {1};".format(tmp_id + 1, args[0])) c("uint64_t tmp{0} = tmp{1} ? tmp{2} / tmp{1} : 0;".format(tmp_id + 2, tmp_id + 1, tmp_id)) return tmp_id + 3 def emit_umul(tmp_id, args): c("uint64_t tmp{0} = {1} * {2};".format(tmp_id, args[1], args[0])) return tmp_id + 1 def emit_usub(tmp_id, args): c("uint64_t tmp{0} = {1} - {2};".format(tmp_id, args[1], args[0])) return tmp_id + 1 def emit_umin(tmp_id, args): c("uint64_t tmp{0} = MIN({1}, {2});".format(tmp_id, args[1], args[0])) return tmp_id + 1 def emit_lshft(tmp_id, args): c("uint64_t tmp{0} = {1} << {2};".format(tmp_id, args[1], args[0])) return tmp_id + 1 def emit_rshft(tmp_id, args): c("uint64_t tmp{0} = {1} >> {2};".format(tmp_id, args[1], args[0])) return tmp_id + 1 def emit_and(tmp_id, args): c("uint64_t tmp{0} = {1} & {2};".format(tmp_id, args[1], args[0])) return tmp_id + 1 ops = {} # (n operands, emitter1, emitter2) ops["FADD"] = (2, emit_fadd, mathml_splice_add) ops["FDIV"] = (2, emit_fdiv, mathml_splice_div) ops["FMAX"] = (2, emit_fmax, mathml_splice_max) ops["FMUL"] = (2, emit_fmul, mathml_splice_mul) ops["FSUB"] = (2, emit_fsub, mathml_splice_sub) ops["READ"] = (2, emit_read, mathml_splice_read) ops["READ_REG"] = (1, emit_read_reg, mathml_splice_read_reg) ops["UADD"] = (2, emit_uadd, mathml_splice_add) ops["UDIV"] = (2, emit_udiv, mathml_splice_div) ops["UMUL"] = (2, emit_umul, mathml_splice_mul) ops["USUB"] = (2, emit_usub, mathml_splice_sub) ops["UMIN"] = (2, emit_umin, mathml_splice_min) ops["<<"] = (2, emit_lshft, mathml_splice_lshft) ops[">>"] = (2, emit_rshft, mathml_splice_rshft) ops["AND"] = (2, emit_and, mathml_splice_and) def brkt(subexp): if " " in subexp: return "(" + subexp + ")" else: return subexp def splice_bitwise_and(args): return brkt(args[1]) + " & " + brkt(args[0]) def splice_logical_and(args): return brkt(args[1]) + " && " + brkt(args[0]) def splice_ult(args): return brkt(args[1]) + " < " + brkt(args[0]) def splice_ugte(args): return brkt(args[1]) + " >= " + brkt(args[0]) exp_ops = {} # (n operands, splicer) exp_ops["AND"] = (2, splice_bitwise_and) exp_ops["UGTE"] = (2, splice_ugte) exp_ops["ULT"] = (2, splice_ult) exp_ops["&&"] = (2, splice_logical_and) hw_vars = { "$EuCoresTotalCount": { 'c': "devinfo->n_eus", 'desc': "The total number of execution units" }, "$EuSlicesTotalCount": { 'c': "devinfo->n_eu_slices" }, "$EuSubslicesTotalCount": { 'c': "devinfo->n_eu_sub_slices" }, "$EuThreadsCount": { 'c': "devinfo->eu_threads_count" }, "$SliceMask": { 'c': "devinfo->slice_mask" }, # subslice_mask is interchangeable with subslice/dual-subslice # Gen12+ only has dual subslices which can be assimilated with # 16EUs subslices. "$SubsliceMask": { 'c': "devinfo->subslice_mask" }, "$DualSubsliceMask": { 'c': "devinfo->subslice_mask" }, "$GpuTimestampFrequency": { 'c': "devinfo->timestamp_frequency" }, "$GpuMinFrequency": { 'c': "devinfo->gt_min_freq" }, "$GpuMaxFrequency": { 'c': "devinfo->gt_max_freq" }, "$SkuRevisionId": { 'c': "devinfo->revision" }, "$QueryMode": { 'c': "devinfo->query_mode" }, } def splice_mathml_expression(set, equation, tag): tokens = equation.split() mathml_stack = [] tmp_xml_operand = "" for token in tokens: if not mathml_stack: token = check_operand_type(set, token) mathml_stack.append([token, default_precedence]) while mathml_stack and mathml_stack[-1][0] in ops: op = mathml_stack.pop()[0] argc, callback, mathml_callback = ops[op] xml_args = [] for i in range(0, argc): xml_operand = mathml_stack.pop() xml_args.append(xml_operand) tmp_xml_operand = mathml_callback(set, xml_args) mathml_stack.append(tmp_xml_operand) xml_string = mathml_stack.pop()[0] equation_descr = "" + tag + " = " return "" + equation_descr + xml_string + "" def output_rpn_equation_code(set, counter, equation): c("/* RPN equation: " + equation + " */") tokens = equation.split() stack = [] tmp_id = 0 tmp = None for token in tokens: stack.append(token) while stack and stack[-1] in ops: op = stack.pop() argc, callback, mathml_callback = ops[op] args = [] for i in range(0, argc): operand = stack.pop() if operand[0] == "$": if operand in hw_vars: operand = hw_vars[operand]['c'] elif operand in set.counter_vars: reference = set.counter_vars[operand] operand = set.read_funcs[operand[1:]] + "(devinfo, metric_set, accumulator)" else: raise Exception("Failed to resolve variable " + operand + " in equation " + equation + " for " + set.name + " :: " + counter.get('name')); args.append(operand) tmp_id = callback(tmp_id, args) tmp = "tmp{0}".format(tmp_id - 1) stack.append(tmp) if len(stack) != 1: raise Exception("Spurious empty rpn code for " + set.name + " :: " + counter.get('name') + ".\nThis is probably due to some unhandled RPN function, in the equation \"" + equation + "\"") value = stack[-1] if value in hw_vars: value = hw_vars[value]['c'] if value in set.counter_vars: value = set.read_funcs[value[1:]] + "(devinfo, metric_set, accumulator)" c("\nreturn " + value + ";") def splice_rpn_expression(set, counter_name, expression): tokens = expression.split() stack = [] for token in tokens: stack.append(token) while stack and stack[-1] in exp_ops: op = stack.pop() argc, callback = exp_ops[op] args = [] for i in range(0, argc): operand = stack.pop() if operand[0] == "$": if operand in hw_vars: operand = hw_vars[operand]['c'] else: raise Exception("Failed to resolve variable " + operand + " in expression " + expression + " for " + set.name + " :: " + counter_name) args.append(operand) subexp = callback(args) stack.append(subexp) if len(stack) != 1: raise Exception("Spurious empty rpn expression for " + set.name + " :: " + counter_name + ".\nThis is probably due to some unhandled RPN operation, in the expression \"" + expression + "\"") return stack[-1] def data_type_to_ctype(ret_type): if ret_type == "uint64": return "uint64_t" elif ret_type == "float": return "double" else: raise Exception("Unhandled case for mapping \"" + ret_type + "\" to a C type") def output_counter_read(gen, set, counter): c("\n") c("/* {0} :: {1} */".format(set.name, counter.get('name'))) if counter.read_hash in hashed_funcs: c("#define %s \\" % counter.read_sym) c.indent(4) c("%s" % hashed_funcs[counter.read_hash]) c.outdent(4) else: ret_type = counter.get('data_type') ret_ctype = data_type_to_ctype(ret_type) read_eq = counter.get('equation') c("static " + ret_ctype) c(counter.read_sym + "(const struct gputop_devinfo *devinfo,\n") c.indent(len(counter.read_sym) + 1) c("const struct gputop_metric_set *metric_set,\n") c("uint64_t *accumulator)\n") c.outdent(len(counter.read_sym) + 1) c("{") c.indent(4) output_rpn_equation_code(set, counter, read_eq) c.outdent(4) c("}") hashed_funcs[counter.read_hash] = counter.read_sym def output_counter_max(gen, set, counter): max_eq = counter.get('max_equation') if not max_eq or max_eq == "100": return c("\n") c("/* {0} :: {1} */".format(set.name, counter.get('name'))) if counter.max_hash in hashed_funcs: c("#define %s \\" % counter.max_sym) c.indent(4) c("%s" % hashed_funcs[counter.max_hash]) c.outdent(4) else: ret_type = counter.get('data_type') ret_ctype = data_type_to_ctype(ret_type) c("static " + ret_ctype) c(counter.max_sym + "(const struct gputop_devinfo *devinfo,\n") c.indent(len(counter.max_sym) + 1) c("const struct gputop_metric_set *metric_set,\n") c("uint64_t *accumulator)\n") c.outdent(len(counter.max_sym) + 1) c("{") c.indent(4) output_rpn_equation_code(set, counter, max_eq) c.outdent(4) c("}") hashed_funcs[counter.max_hash] = counter.max_sym semantic_type_map = { "duration": "raw", "ratio": "event" } def output_availability(set, availability, counter_name): expression = splice_rpn_expression(set, counter_name, availability) lines = expression.split(' && ') n_lines = len(lines) if n_lines == 1: c("if (" + lines[0] + ") {") else: c("if (" + lines[0] + " &&") c.indent(4) for i in range(1, (n_lines - 1)): c(lines[i] + " &&") c(lines[(n_lines - 1)] + ") {") c.outdent(4) def output_units(unit): return unit.replace(' ', '_').upper() def output_counter_report(set, counter): data_type = counter.get('data_type') data_type_uc = data_type.upper() c_type = data_type if "uint" in c_type: c_type = c_type + "_t" semantic_type = counter.get('semantic_type') if semantic_type in semantic_type_map: semantic_type = semantic_type_map[semantic_type] semantic_type_uc = semantic_type.upper() c("\n") availability = counter.get('availability') if availability: output_availability(set, availability, counter.get('name')) c.indent(4) c("counter = &metric_set->counters[metric_set->n_counters++];\n") c("counter->metric_set = metric_set;\n") c("counter->oa_counter_read_{0} = {1};\n".format(data_type, set.read_funcs[counter.get('symbol_name')])) c("counter->name = \"{0}\";\n".format(counter.get('name'))) c("counter->symbol_name = \"{0}\";\n".format(counter.get('symbol_name'))); c("counter->desc = \"{0}\";\n".format(counter.get('description'))) c("counter->type = GPUTOP_PERFQUERY_COUNTER_{0};\n".format(semantic_type_uc)) c("counter->data_type = GPUTOP_PERFQUERY_COUNTER_DATA_{0};\n".format(data_type_uc)) c("counter->units = GPUTOP_PERFQUERY_COUNTER_UNITS_{0};\n".format(output_units(counter.get('units')))) c("counter->max_{0} = {1};\n".format(data_type, set.max_funcs[counter.get('symbol_name')])) c("gputop_gen_add_counter(gen, counter, \"{0}\");\n".format(counter.get('mdapi_group'))) if availability: c.outdent(4) c("}\n") def generate_register_configs(set): register_types = { 'FLEX': 'flex_regs', 'NOA': 'mux_regs', 'OA': 'b_counter_regs', } # allocate memory total_n_registers = {} register_configs = set.findall('register_config') for register_config in register_configs: t = register_types[register_config.get('type')] if t not in total_n_registers: total_n_registers[t] = len(register_config.findall('register')) else: total_n_registers[t] += len(register_config.findall('register')) for reg in total_n_registers: c("metric_set->%s = rzalloc_array(metric_set, struct gputop_register_prog, %i);" % (reg, total_n_registers[reg])) c("\n") # fill in register/values register_configs = set.findall('register_config') for register_config in register_configs: t = register_types[register_config.get('type')] availability = register_config.get('availability') if availability: output_availability(set, availability, register_config.get('type') + ' register config') c.indent(4) for register in register_config.findall('register'): c("metric_set->%s[metric_set->n_%s++] = (struct gputop_register_prog) { .reg = %s, .val = %s };" % (t, t, register.get('address'), register.get('value'))) if availability: c.outdent(4) c("}") c("\n") # class Counter: def __init__(self, set, xml): self.xml = xml self.set = set self.read_hash = None self.max_hash = None self.read_sym = "{0}__{1}__{2}__read".format(self.set.gen.chipset, self.set.underscore_name, self.xml.get('underscore_name')) max_eq = self.xml.get('max_equation') if not max_eq: self.max_sym = "NULL /* undefined */" elif max_eq == "100": self.max_sym = "percentage_max_callback_" + self.xml.get('data_type') else: self.max_sym = "{0}__{1}__{2}__max".format(self.set.gen.chipset, self.set.underscore_name, self.xml.get('underscore_name')) def get(self, prop): return self.xml.get(prop) def compute_hashes(self): if self.read_hash is not None: return def replace_func(token): if token[0] != "$": return token if token not in self.set.counter_vars: return token self.set.counter_vars[token].compute_hashes() return self.set.counter_vars[token].read_hash read_eq = self.xml.get('equation') self.read_hash = ' '.join(map(replace_func, read_eq.split())) max_eq = self.xml.get('max_equation') if max_eq: self.max_hash = ' '.join(map(replace_func, max_eq.split())) class Set: def __init__(self, gen, xml): self.gen = gen self.xml = xml self.counter_vars = {} self.max_funcs = {} self.read_funcs = {} self.counter_hashes = {} self.counters = [] xml_counters = self.xml.findall("counter") for xml_counter in xml_counters: counter = Counter(self, xml_counter) self.counters.append(counter) self.counter_vars["$" + counter.get('symbol_name')] = counter self.max_funcs[counter.get('symbol_name')] = counter.max_sym self.read_funcs[counter.get('symbol_name')] = counter.read_sym for counter in self.counters: counter.compute_hashes() @property def hw_config_guid(self): return self.xml.get('hw_config_guid') @property def name(self): return self.xml.get('name') @property def symbol_name(self): return self.xml.get('symbol_name') @property def underscore_name(self): return self.xml.get('underscore_name') def findall(self, path): return self.xml.findall(path) def find(self, path): return self.xml.find(path) class Gen: def __init__(self, filename): self.filename = filename self.xml = et.parse(self.filename) self.chipset = self.xml.find('.//set').get('chipset').lower() self.sets = [] for xml_set in self.xml.findall(".//set"): self.sets.append(Set(self, xml_set)) def main(): global c global h global xml_equations parser = argparse.ArgumentParser() parser.add_argument("--header", help="Header file to write") parser.add_argument("--code", help="C file to write") parser.add_argument("--xml-out", help="Output XML files (adding mathml equations)") parser.add_argument("xml_files", nargs='+', help="List of xml metrics files to process") args = parser.parse_args() # Note: either arg may == None h = codegen.Codegen(args.header) c = codegen.Codegen(args.code) gens = [] for xml_file in args.xml_files: gens.append(Gen(xml_file)) if args.xml_out: for gen in gens: for set in gen.sets: for counter in set.counters: xml_equation = splice_mathml_expression(set, counter.get('equation'), "EQ") counter.append(et.fromstring(xml_equation)) gen.xml.write(gen.filename) copyright = textwrap.dedent("""\ /* Autogenerated file, DO NOT EDIT manually! generated by {} * * Copyright (c) 2018 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ """).format(os.path.basename(__file__)) h(copyright) c(copyright) c(textwrap.dedent("""\ #include #include #include #include """)) c("#include \"" + os.path.basename(args.header) + "\"") c(textwrap.dedent("""\ #include #include #include "gputop-oa-metrics.h" #include "util/ralloc.h" #define MIN(x, y) (((x) < (y)) ? (x) : (y)) #define MAX(a, b) (((a) > (b)) ? (a) : (b)) static double percentage_max_callback_float(const struct gputop_devinfo *devinfo, const struct gputop_metric_set *metric_set, uint64_t *accumulator) { return 100; } static uint64_t percentage_max_callback_uint64(const struct gputop_devinfo *devinfo, const struct gputop_metric_set *metric_set, uint64_t *accumulator) { return 100; } """)) # Print out all equation functions. for gen in gens: for set in gen.sets: for counter in set.counters: output_counter_read(gen, set, counter) output_counter_max(gen, set, counter) # Print out all set registration functions for each set in each # generation. for gen in gens: for set in gen.sets: c("\nstatic void\n") c(gen.chipset + "_add_" + set.underscore_name + "_metric_set(struct gputop_gen *gen,") c.indent(4) c("const struct gputop_devinfo *devinfo)") c.outdent(4) c("{\n") c.indent(4) c("struct gputop_metric_set *metric_set;\n") c("struct gputop_metric_set_counter *counter;\n\n") counters = sorted(set.counters, key=lambda k: k.get('symbol_name')) c("metric_set = rzalloc(gen, struct gputop_metric_set);\n") c("metric_set->name = \"" + set.name + "\";\n") c("metric_set->symbol_name = \"" + set.symbol_name + "\";\n") c("metric_set->hw_config_guid = \"" + set.hw_config_guid + "\";\n") c("metric_set->counters = rzalloc_array(metric_set, struct gputop_metric_set_counter, {0});\n".format(str(len(counters)))) c("metric_set->n_counters = 0;\n") c("metric_set->perf_oa_metrics_set = 0; // determined at runtime\n") if gen.chipset == "hsw": c(textwrap.dedent("""\ metric_set->perf_oa_format = I915_OA_FORMAT_A45_B8_C8; metric_set->perf_raw_size = 256; metric_set->gpu_time_offset = 0; metric_set->a_offset = 1; metric_set->b_offset = metric_set->a_offset + 45; metric_set->c_offset = metric_set->b_offset + 8; """)) else: c(textwrap.dedent("""\ metric_set->perf_oa_format = I915_OA_FORMAT_A32u40_A4u32_B8_C8; metric_set->perf_raw_size = 256; metric_set->gpu_time_offset = 0; metric_set->gpu_clock_offset = 1; metric_set->a_offset = 2; metric_set->b_offset = metric_set->a_offset + 36; metric_set->c_offset = metric_set->b_offset + 8; """)) c("gputop_gen_add_metric_set(gen, metric_set);"); c("\n") generate_register_configs(set) for counter in counters: output_counter_report(set, counter) c("\nassert(metric_set->n_counters <= {0});\n".format(len(counters))); c.outdent(4) c("}\n") h(textwrap.dedent("""\ #pragma once #include "gputop-oa-metrics.h" #ifdef __cplusplus extern "C" { #endif """)) # Print out all set registration functions for each generation. for gen in gens: h("struct gputop_gen *gputop_oa_get_metrics_" + gen.chipset + "(const struct gputop_devinfo *devinfo);\n\n") c("\nstruct gputop_gen *") c("gputop_oa_get_metrics_" + gen.chipset + "(const struct gputop_devinfo *devinfo)") c("{") c.indent(4) c("struct gputop_gen *gen = gputop_gen_new();\n") c("\n") for set in gen.sets: c("{0}_add_{1}_metric_set(gen, devinfo);".format(gen.chipset, set.underscore_name)) c("\n") c("return gen;") c.outdent(4) c("}") h(textwrap.dedent("""\ #ifdef __cplusplus } /* extern C */ #endif """)) if __name__ == '__main__': main() ================================================ FILE: scripts/i915-perf-kernelgen.py ================================================ #!/usr/bin/env python3 # Copyright (C) 2015-2016 Intel Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Generates code for metric sets supported by the drm i915-perf driver # including: # # - Static arrays describing the various NOA/Boolean/OA register configs # - Functions/structs for advertising metrics via sysfs # - Code that can evaluate which configs are available for the current system # based on the RPN availability equations # import argparse import copy import datetime import hashlib from operator import itemgetter import re import sys import xml.etree.cElementTree as et import pylibs.codegen as codegen import pylibs.oa_guid_registry as oa_registry default_set_blacklist = {} def underscore(name): s = re.sub('MHz', 'Mhz', name) s = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s).lower() def print_err(*args): sys.stderr.write(' '.join(map(str,args)) + '\n') def brkt(subexp): if " " in subexp: return "(" + subexp + ")" else: return subexp def splice_bitwise_and(args): return brkt(args[1]) + " & " + brkt(args[0]) def splice_logical_and(args): return brkt(args[1]) + " && " + brkt(args[0]) def splice_ult(args): return brkt(args[1]) + " < " + brkt(args[0]) def splice_ugte(args): return brkt(args[1]) + " >= " + brkt(args[0]) exp_ops = {} # (n operands, splicer) exp_ops["AND"] = (2, splice_bitwise_and) exp_ops["UGTE"] = (2, splice_ugte) exp_ops["ULT"] = (2, splice_ult) exp_ops["&&"] = (2, splice_logical_and) c_syms = {} c_syms["$SliceMask"] = "INTEL_INFO(dev_priv)->sseu.slice_mask" c_syms["$SubsliceMask"] = "INTEL_INFO(dev_priv)->sseu.subslice_mask" c_syms["$SkuRevisionId"] = "dev_priv->drm.pdev->revision" mnemonic_syms = {} mnemonic_syms["$SliceMask"] = "slices" mnemonic_syms["$SubsliceMask"] = "subslices" mnemonic_syms["$SkuRevisionId"] = "sku" source_copyright = """// SPDX-License-Identifier: MIT /* * Copyright © 2018-{year} Intel Corporation * * Autogenerated file by GPU Top : https://github.com/rib/gputop * DO NOT EDIT manually! */ """ header_copyright = """/* SPDX-License-Identifier: MIT */ /* * Copyright © 2018-{year} Intel Corporation * * Autogenerated file by GPU Top : https://github.com/rib/gputop * DO NOT EDIT manually! */ """ def output_b_counter_config(metric_set, config): c("\nstatic const struct i915_oa_reg b_counter_config_" + metric_set['perf_name_lc'] + "[] = {") c.indent(8) n_regs = 0 for reg in config.findall("register"): assert reg.get('type') == 'OA' addr = int(reg.get('address'), 16) addr_str = "0x%x" % addr val = int(reg.get('value'), 16) val_str = "0x%08x" % val c("{ _MMIO(" + addr_str + "), " + val_str + " },") n_regs = n_regs + 1 c.outdent(8) c("};") def output_flex_config(metric_set, config): c("\nstatic const struct i915_oa_reg flex_eu_config_" + metric_set['perf_name_lc'] + "[] = {") c.indent(8) n_regs = 0 for reg in config.findall("register"): assert reg.get('type') == 'FLEX' addr = int(reg.get('address'), 16) addr_str = "0x%x" % addr val = int(reg.get('value'), 16) val_str = "0x%08x" % val c("{ _MMIO(" + addr_str + "), " + val_str + " },") n_regs = n_regs + 1 c.outdent(8) c("};") def exp_to_symbol(exp): exp = exp.replace(' & ', '_') exp = exp.replace(' && ', '_and_') exp = exp.replace(' >= ', '_gte_') exp = exp.replace(' < ', '_lt_') exp = exp.replace(' ', '_') exp = exp.replace('(', '') exp = exp.replace(')', '') exp = exp.replace(')', '') return exp def count_config_mux_registers(config): n_regs = 0 for reg in config.findall("register"): if reg.get('type') == 'NOA': addr = reg.get('address') n_regs = n_regs + 1 return n_regs def output_mux_config(metric_set, config): c("\nstatic const struct i915_oa_reg mux_config_" + metric_set['perf_name_lc'] + "[] = {") c.indent(8) for reg in config.findall("register"): assert reg.get('type') == 'NOA' addr = int(reg.get('address'), 16) addr_str = "0x%x" % addr val = int(reg.get('value'), 16) val_str = "0x%08x" % val c("{ _MMIO(" + addr_str + "), " + val_str + " },") c.outdent(8) c("};") def output_config(metric_set, config): c("\mstatic const struct i915_oa_config_" + metric_set['perf_name_lc'] + " = {") c.indent(8) c(".uuid = \"" + metric_set['guid'] + "\","); c(".id = 1,") c("\n") c(".mux_regs = mux_config_" + metric_set['perf_name_lc'] + "_oa,") c(".mux_regs_len = ARRAY_SIZE(mux_config_" + metric_set['perf_name_lc'] + "_oa),") c("\n") c(".b_counter_regs = b_counter_config_" + metric_set['perf_name_lc'] + "_oa,") c(".b_counter_regs_len = ARRAY_SIZE(b_counter_config_" + metric_set['perf_name_lc'] + "_oa),") c("\n") c(".flex_eu_regs = flex_eu_config_" + metric_set['perf_name_lc'] + "_oa,") c(".flex_eu_counter_regs_len = ARRAY_SIZE(flex_eu_config_" + metric_set['perf_name_lc'] + "_oa),") c("\n") c(".sysfs_metric = {") c.indent(8) c(".name = \"" + metric_set['guid'] + "\",") c.outdent(8) c("},") c.outdent(8) c("};") def output_config_select(metric_set): c("dev_priv->perf.oa.mux_regs =") c.indent(8) c("mux_config_" + metric_set['perf_name_lc'] + ";") c.outdent(8) c("dev_priv->perf.oa.mux_regs_len =") c.indent(8) c("ARRAY_SIZE(mux_config_" + metric_set['perf_name_lc'] + ");") c.outdent(8) c("\n") c("dev_priv->perf.oa.b_counter_regs =") c.indent(8) c("b_counter_config_" + metric_set['perf_name_lc'] + ";") c.outdent(8) c("dev_priv->perf.oa.b_counter_regs_len =") c.indent(8) c("ARRAY_SIZE(b_counter_config_" + metric_set['perf_name_lc'] + ");") c.outdent(8) c("\n") c("dev_priv->perf.oa.flex_regs =") c.indent(8) c("flex_eu_config_" + metric_set['perf_name_lc'] + ";") c.outdent(8) c("dev_priv->perf.oa.flex_regs_len =") c.indent(8) c("ARRAY_SIZE(flex_eu_config_" + metric_set['perf_name_lc'] + ");") c.outdent(8) def output_sysfs_code(sets): for metric_set in sets: perf_name = metric_set['perf_name'] perf_name_lc = metric_set['perf_name_lc'] c("\n") c("static ssize_t") c("show_" + perf_name_lc + "_id(struct device *kdev, struct device_attribute *attr, char *buf)") c("{") c.indent(8) c("return sprintf(buf, \"1\\n\");") c.outdent(8) c("}") h("void i915_perf_load_test_config_" + chipset.lower() + "(struct drm_i915_private *dev_priv);") h("\n") c("\n") c("void") c("i915_perf_load_test_config_" + chipset.lower() + "(struct drm_i915_private *dev_priv)") c("{") c.indent(8) for metric_set in sets: c("strlcpy(dev_priv->perf.oa.test_config.uuid,") c.indent(8) c("\"" + metric_set['guid'] + "\",") c("sizeof(dev_priv->perf.oa.test_config.uuid));") c.outdent(8) c("dev_priv->perf.oa.test_config.id = 1;") c("\n") c("dev_priv->perf.oa.test_config.mux_regs = mux_config_" + metric_set['perf_name_lc'] + ";") c("dev_priv->perf.oa.test_config.mux_regs_len = ARRAY_SIZE(mux_config_" + metric_set['perf_name_lc'] + ");") c("\n") c("dev_priv->perf.oa.test_config.b_counter_regs = b_counter_config_" + metric_set['perf_name_lc'] + ";") c("dev_priv->perf.oa.test_config.b_counter_regs_len = ARRAY_SIZE(b_counter_config_" + metric_set['perf_name_lc'] + ");") c("\n") c("dev_priv->perf.oa.test_config.flex_regs = flex_eu_config_" + metric_set['perf_name_lc'] + ";") c("dev_priv->perf.oa.test_config.flex_regs_len = ARRAY_SIZE(flex_eu_config_" + metric_set['perf_name_lc'] + ");") c("\n") c("dev_priv->perf.oa.test_config.sysfs_metric.name = \"" + metric_set['guid'] + "\";") c("dev_priv->perf.oa.test_config.sysfs_metric.attrs = dev_priv->perf.oa.test_config.attrs;") c("\n") c("dev_priv->perf.oa.test_config.attrs[0] = &dev_priv->perf.oa.test_config.sysfs_metric_id.attr;") c("\n") c("dev_priv->perf.oa.test_config.sysfs_metric_id.attr.name = \"id\";") c("dev_priv->perf.oa.test_config.sysfs_metric_id.attr.mode = 0444;") c("dev_priv->perf.oa.test_config.sysfs_metric_id.show = show_" + metric_set['perf_name_lc'] + "_id;") c.outdent(8) c("}") parser = argparse.ArgumentParser() parser.add_argument("xml", nargs="+", help="XML description of metrics") parser.add_argument("--guids", required=True, help="Metric set GUID registry") parser.add_argument("--chipset", required=True, help="Chipset being output for") parser.add_argument("--c-out", required=True, help="Filename for generated C code") parser.add_argument("--h-out", required=True, help="Filename for generated header") parser.add_argument("--sysfs", action="store_true", help="Output code for sysfs") parser.add_argument("--whitelist", help="Override default metric set whitelist") parser.add_argument("--no-whitelist", action="store_true", help="Bypass default metric set whitelist") parser.add_argument("--blacklist", help="Don't generate anything for given metric sets") args = parser.parse_args() guids = {} chipset = args.chipset.upper() guids_xml = et.parse(args.guids) for guid in guids_xml.findall(".//guid"): if 'config_hash' in guid.attrib: hashing_key = oa_registry.Registry.chipset_derive_hash(guid.get('chipset'), guid.get('config_hash')) guids[hashing_key] = guid.get('id') # Note: either filename argument may == None h = codegen.Codegen(args.h_out); h.use_tabs = True c = codegen.Codegen(args.c_out); c.use_tabs = True year = datetime.date.today().year h(header_copyright.format(year=year)) h("#ifndef __I915_OA_" + chipset + "_H__\n") h("#define __I915_OA_" + chipset + "_H__\n\n") h("struct drm_i915_private;\n\n") c(source_copyright.format(year=year)) if args.sysfs: c("#include ") c("\n") c("#include \"i915_drv.h\"\n") c("#include \"i915_oa_" + args.chipset + ".h\"\n") sets = [] for arg in args.xml: xml = et.parse(arg) for set_element in xml.findall(".//set"): assert set_element.get('chipset') == chipset set_name = set_element.get('symbol_name') # Exception on Haswell, which doesn't have a test config. if chipset == 'HSW': if set_name != 'RenderBasic': continue elif set_name != 'TestOa': continue if args.whitelist: set_whitelist = args.whitelist.split() if set_name not in set_whitelist: continue if args.blacklist: set_blacklist = args.blacklist.split() else: set_blacklist = default_set_blacklist if set_name in set_blacklist: continue configs = set_element.findall("register_config") if len(configs) == 0: print_err("WARNING: Missing register configuration for set \"" + set_element.get('name') + "\" (SKIPPING)") continue hw_config_hash = oa_registry.Registry.hw_config_hash(set_element) hashing_key = oa_registry.Registry.chipset_derive_hash(chipset.lower(), hw_config_hash) if hashing_key not in guids: print_err("WARNING: No GUID found for metric set " + chipset + ", " + set_element.get('name') + " (expected key = " + hashing_key + ") (SKIPPING)") continue perf_name_lc = underscore(set_name) perf_name = perf_name_lc.upper() metric_set = { 'name': set_name, 'set_element': set_element, 'chipset_lc': chipset.lower(), 'perf_name_lc': perf_name_lc, 'perf_name': perf_name, 'guid': guids[hashing_key], 'configs': configs } sets.append(metric_set) for metric_set in sets: set_name = metric_set['name'] configs = metric_set['configs'] mux_configs = [] b_counter_configs = [] flex_configs = [] for config in configs: config_type = config.get('type') if config_type == "NOA": mux_configs.append(config) elif config_type == "OA": b_counter_configs.append(config) elif config_type == "FLEX": flex_configs.append(config) if len(b_counter_configs) == 0: empty = et.Element('register_config') b_counter_configs.append(empty) assert len(b_counter_configs) == 1 output_b_counter_config(metric_set, b_counter_configs[0]) if len(flex_configs) == 0: empty = et.Element('register_config') flex_configs.append(empty) assert len(flex_configs) == 1 output_flex_config(metric_set, flex_configs[0]) assert len(mux_configs) == 1 output_mux_config(metric_set, mux_configs[0]) if args.sysfs: output_sysfs_code(sets) h("#endif\n") ================================================ FILE: scripts/mdapi-xml-convert.py ================================================ #!/usr/bin/env python2 # Copyright (C) 2015-2016 Intel Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # "MDAPI" xml files are an XML schema for maintaining meta data about Gen # graphics Ovservability counters, where MD API is the name of a library shared # by Intel GPA and Intel VTune. # # These files aren't publicly documented and have some historical baggage that # adds some complexity as well as being inconsistent in a number of ways that # makes it quite a bit of effort to parse/use the data. We also don't have # guarantees about how this schema is maintained. # # We've taken the opportunity to find ways to simplify the input data and to # make it more consistent to hopefully reduce the effort involved in using the # data downstream. # import argparse import copy import hashlib from operator import itemgetter import re import sys import time import uuid import xml.etree.ElementTree as et import xml.sax.saxutils as saxutils import pylibs.oa_guid_registry as oa_registry # MDAPI configs include writes to some non-config registers, # thus the blacklists... gen8_11_chipset_params = { 'a_offset': 16, 'b_offset': 192, 'c_offset': 224, 'oa_report_size': 256, 'config_reg_blacklist': { 0x2364, # OACTXID }, } chipsets = { 'HSW': { 'a_offset': 12, 'b_offset': 192, 'c_offset': 224, 'oa_report_size': 256, 'registers': { # TODO extend the symbol table for nicer output... 0x2710: { 'name': 'OASTARTTRIG1' }, 0x2714: { 'name': 'OASTARTTRIG1' }, 0x2718: { 'name': 'OASTARTTRIG1' }, 0x271c: { 'name': 'OASTARTTRIG1' }, 0x2720: { 'name': 'OASTARTTRIG1' }, 0x2724: { 'name': 'OASTARTTRIG6' }, 0x2728: { 'name': 'OASTARTTRIG7' }, 0x272c: { 'name': 'OASTARTTRIG8' }, 0x2740: { 'name': 'OAREPORTTRIG1' }, 0x2744: { 'name': 'OAREPORTTRIG2' }, 0x2748: { 'name': 'OAREPORTTRIG3' }, 0x274c: { 'name': 'OAREPORTTRIG4' }, 0x2750: { 'name': 'OAREPORTTRIG5' }, 0x2754: { 'name': 'OAREPORTTRIG6' }, 0x2758: { 'name': 'OAREPORTTRIG7' }, 0x275c: { 'name': 'OAREPORTTRIG8' }, 0x2770: { 'name': 'OACEC0_0' }, 0x2774: { 'name': 'OACEC0_1' }, 0x2778: { 'name': 'OACEC1_0' }, 0x277c: { 'name': 'OACEC1_1' }, 0x2780: { 'name': 'OACEC2_0' }, 0x2784: { 'name': 'OACEC2_1' }, 0x2788: { 'name': 'OACEC3_0' }, 0x278c: { 'name': 'OACEC3_1' }, 0x2790: { 'name': 'OACEC4_0' }, 0x2794: { 'name': 'OACEC4_1' }, 0x2798: { 'name': 'OACEC5_0' }, 0x279c: { 'name': 'OACEC5_1' }, 0x27a0: { 'name': 'OACEC6_0' }, 0x27a4: { 'name': 'OACEC6_1' }, 0x27a8: { 'name': 'OACEC7_0' }, 0x27ac: { 'name': 'OACEC7_1' }, }, 'config_reg_blacklist': { 0x2364, # OASTATUS1 register }, }, 'BDW': gen8_11_chipset_params, 'CHV': gen8_11_chipset_params, 'SKLGT2': gen8_11_chipset_params, 'SKLGT3': gen8_11_chipset_params, 'SKLGT4': gen8_11_chipset_params, 'BXT': gen8_11_chipset_params, 'KBLGT2': gen8_11_chipset_params, 'KBLGT3': gen8_11_chipset_params, 'GLK': gen8_11_chipset_params, 'CFLGT2': gen8_11_chipset_params, 'CFLGT3': gen8_11_chipset_params, 'CNL': gen8_11_chipset_params, 'ICL': gen8_11_chipset_params, 'LKF': gen8_11_chipset_params, 'TGL': gen8_11_chipset_params, } register_types = { 'OA', 'NOA', 'FLEX', 'PM' } default_set_blacklist = { "RenderDX1x", # TODO: rename to something non 'DX' # specific if this config is generally # usefull "RenderBalance", # XXX: missing register config } counter_blacklist = { "DramLlcThroughput", # TODO: The max equation of this counter # requires dram throughtput value. Need to # investiguate how to get this value. } sys_vars = { "EuCoresTotalCount", "EuSlicesTotalCount", "SamplersTotalCount", "EuThreadsCount", "GpuMinFrequencyMHz", "GpuMaxFrequencyMHz", "GpuTimestampFrequency", "SliceMask", "SubsliceMask", "EuSubslicesTotalCount" } def underscore(name): s = re.sub('MHz', 'Mhz', name) s = re.sub('\.', '_', s) s = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s).lower() def print_err(*args): sys.stderr.write(' '.join(map(str,args)) + '\n') read_register_offsets = { 0x1f0: 'PERFCNT1', 0x1f8: 'PERFCNT2', } def read_value(chipset, offset): if offset in read_register_offsets: return read_register_offsets[offset] print_err("Unknown offset register at offset {0}".format(offset)) assert 0 def read_token_to_rpn_read(chipset, token, raw_offsets): width, offset_str = token.split('@') # For Broadwell the raw read notation was extended for 40 bit # counters: rd40@<32bit_part1_offset>:<8bit_part2_offset> if width == "rd40": offset_32_str, offset_8_str = offset_str.split(':') offset_str = offset_32_str offset = int(offset_str, 16) if raw_offsets: a_offset = chipsets[chipset]['a_offset'] b_offset = chipsets[chipset]['b_offset'] c_offset = chipsets[chipset]['c_offset'] report_size = chipsets[chipset]['oa_report_size'] if offset < a_offset: if offset == 4: return "GPU_TIME 0 READ" elif offset == 12: assert chipset != "HSW" # Only for Gen8+ return "GPU_CLOCK 0 READ" else: assert 0 elif offset < b_offset: return "A " + str((offset - a_offset) / 4) + " READ" elif offset < c_offset: return "B " + str((offset - b_offset) / 4) + " READ" elif offset < report_size: return "C " + str((offset - c_offset) / 4) + " READ" else: return "{0} READ_REG".format(read_value(chipset, offset)) else: idx = offset / 8 if chipset == "HSW": # On Haswell accumulated counters are assumed to start # with GPU_TIME followed by 45 A counters, then 8 B # counters and finally 8 C counters. if idx < 1: return "GPU_TIME 0 READ" elif idx < 46: return "A " + str(idx - 1) + " READ" elif idx < 54: return "B " + str(idx - 46) + " READ" elif idx < 62: return "C " + str(idx - 54) + " READ" else: return "{0} READ_REG".format(read_value(chipset, offset)) else: # For Gen8+ the array of accumulated counters is # assumed to start with a GPU_TIME then GPU_CLOCK, # then 36 A counters, then 8 B counters and finally # 8 C counters. if idx == 0: return "GPU_TIME 0 READ" elif idx == 1: return "GPU_CLOCK 0 READ" elif idx < 38: return "A " + str(idx - 2) + " READ" elif idx < 46: return "B " + str(idx - 38) + " READ" elif idx < 54: return "C " + str(idx - 46) + " READ" else: return "{0} READ_REG".format(read_value(chipset, offset)) assert 0 def replace_read_tokens_with_rpn_read_ops(chipset, equation, raw_offsets): # MDAPI MetricSet equations use tokens like 'dw@0xff' for reading raw # values from snapshots, but this doesn't seem convenient for a few # reasons: # # 1) The offsets hide the particular a, b, or c counter they # correspond to which in turn makes it awkward to experiment # with different report sizes which trade off how many a, b and # c counters are available # # 2) Raw reads could be represented as RPN operations too, and # the consistency could make them slightly easier for tools to # handle, E.g: # # "A 5 READ" = read A counter 5 # # We replace dw@ address tokens with GPU_TIME, A, B or C READ ops... # tokens = equation.split() equation = "" for token in tokens: if '@' in token: read_exp = read_token_to_rpn_read(chipset, token, raw_offsets) equation = equation + " " + read_exp else: equation = equation + " " + token return equation parser = argparse.ArgumentParser() parser.add_argument("xml", nargs="+", help="XML description of metrics") parser.add_argument("--guids", required=True, help="Metric set GUID registry") parser.add_argument("--whitelist", help="Only output for given, space-separated, sets") parser.add_argument("--blacklist", help="Don't generate anything for given metric sets") parser.add_argument("--merge", help="Additional meta data to merge into the result") parser.add_argument("--dry-run", action="store_true", help="Not generate new XML but to check any errors") args = parser.parse_args() metrics = et.Element('metrics') tree = et.ElementTree(metrics) def apply_aliases(text, aliases): if aliases == None: return text for alias in aliases.split(','): (a, b) = alias.split('|') text = re.sub(r"\b%s\b" % re.escape(a), b, text) a = a.lower() b = b.lower() text = re.sub(r"\b%s\b" % re.escape(a), b, text) return text def strip_dx_apis(text): if text == None: return "" stripped = "" apis = text.split() for api in apis: if api[:2] != "DX": stripped = stripped + " " + api return stripped.strip() # For recursively appending counters in order of dependencies... def append_deps_and_counter(mdapi_counter, mdapi_counters, deps, sorted_array, sorted_set): symbol_name = mdapi_counter.get('SymbolName') if symbol_name in sorted_set: return for dep_name in deps[symbol_name]: if dep_name in mdapi_counters: append_deps_and_counter(mdapi_counters[dep_name], mdapi_counters, deps, sorted_array, sorted_set) sorted_array.append(mdapi_counter) sorted_set[symbol_name] = mdapi_counter def sort_counters(mdapi_counters, deps): sorted_array = [] sorted_set = {} # counters in here have been added to array for symbol_name in mdapi_counters: append_deps_and_counter(mdapi_counters[symbol_name], mdapi_counters, deps, sorted_array, sorted_set) return sorted_array def expand_macros(equation): equation = equation.replace('GpuDuration', "$Self 100 UMUL $GpuCoreClocks FDIV") equation = equation.replace('EuAggrDuration', "$Self $EuCoresTotalCount UDIV 100 UMUL $GpuCoreClocks FDIV") return equation def fixup_equation(equation): if equation is None: return None return equation.replace('$SubliceMask', '$SubsliceMask') # The MDAPI XML files sometimes duplicate the same Flex EU/OA regs # between configs with different AvailabilityEquations even though the # availability checks are only expected to affect the MUX configs # # We iterate all the configs to filter out the FLEX/OA configs and # double check that there's never any variations between repeated # configs # def filter_single_config_registers_of_type(mdapi_metric_set, type): regs = [] for mdapi_reg_config in mdapi_metric_set.findall("RegConfigStart"): tmp_regs = [] for mdapi_reg in mdapi_reg_config.findall("Register"): reg = (int(mdapi_reg.get('offset'),16), int(mdapi_reg.get('value'),16)) if reg[0] in chipsets[chipset]['config_reg_blacklist']: continue if mdapi_reg.get('type') == type: tmp_regs.append(reg) if len(tmp_regs) > 0: bad = False if len(regs) == 0: regs = tmp_regs elif len(regs) != len(tmp_regs): bad = True else: for i in xrange(0, len(regs)): if regs[i] != tmp_regs[i]: bad = True break if bad: print_err("ERROR: multiple, differing FLEX/OA configs for one set: MetricSet=\"" + mdapi_metric_set.get('ShortName')) sys.exit(1) return regs # We only have a very small number of IDs, but we aren't assuming they # start from zero or are contiguous in the MDAPI XML files. Python # doesn't seem to have a built in sparse array type so we just # loop over the entries we have: def get_mux_id_group(id_groups, id): for group in id_groups: if group['id'] == id: return group new_group = { 'id': id, 'configs': [] } id_groups.append(new_group) return new_group def process_mux_configs(mdapi_set): allow_missing_id = True mux_config_id_groups = [] for mdapi_reg_config in mdapi_set.findall("RegConfigStart"): mux_regs = [] for mdapi_reg in mdapi_reg_config.findall("Register"): address = int(mdapi_reg.get('offset'), 16) if address in chipsets[chipset]['config_reg_blacklist']: continue reg_type = mdapi_reg.get('type') if reg_type not in register_types: print_err("ERROR: unknown register type=\"" + reg_type + "\": MetricSet=\"" + mdapi_set.get('ShortName')) sys.exit(1) if reg_type != 'NOA' and reg_type != 'PM': continue reg = (address, int(mdapi_reg.get('value'), 16)) mux_regs.append(reg) if len(mux_regs) == 0: continue availability = mdapi_reg_config.get('AvailabilityEquation') if availability == "": availability = None if mdapi_reg_config.get('ConfigPriority') != None: reg_config_priority = int(mdapi_reg_config.get('ConfigPriority')) else: reg_config_priority = 0 if mdapi_reg_config.get('ConfigId') != None: reg_config_id = int(mdapi_reg_config.get('ConfigId')) allow_missing_id = False elif mdapi_reg_config.get('ConfigId') == None and allow_missing_id == True: reg_config_id = 0 else: # It will spell trouble if there's a mixture of explicit and # implied config IDs... print_err("ERROR: register configs mixing implied/explicit IDs: MetricSet=\"" + mdapi_set.get('ShortName')) sys.exit(1) mux_config = { 'priority': reg_config_priority, 'availability': availability, 'registers': mux_regs } mux_config_id_group = get_mux_id_group(mux_config_id_groups, reg_config_id) mux_config_id_group['configs'].append(mux_config) mux_config_id_groups.sort(key=itemgetter('id')) # The only special case we currently support for more than one group of NOA # MUX configs is for the Broadwell ComputeExtended metric set with two Id # groups and the second just has a single unconditional config that can # logically be appended to all the conditional configs of the first group if len(mux_config_id_groups) > 1: if len(mux_config_id_groups) != 2: print_err("ERROR: Script doesn't currently allow more than two groups of NOA MUX configs for a single metric set: MetricSet=\"" + mdapi_set.get('ShortName')) sys.exit(1) last_id_group = mux_config_id_groups[-1] if len(last_id_group['configs']) != 1: print_err("ERROR: Script currently only allows up to two Ids for NOA MUX configs if second Id only contains a single unconditional config: MetricSet=\"" + mdapi_set.get('ShortName')) sys.exit(1) tail_config = last_id_group['configs'][0] for mux_config in mux_config_id_groups[0]['configs']: mux_config['registers'] = mux_config['registers'] + tail_config['registers'] mux_config_id_groups = [mux_config_id_groups[0]] if len(mux_config_id_groups) == 0 or mux_config_id_groups[0]['configs'] == 0: print_err("ERROR: MUX register configs missing: MetricSet=\"" + mdapi_set.get('ShortName')) sys.exit(1) mux_configs = mux_config_id_groups[0]['configs'] assert isinstance(mux_configs, list) assert len(mux_configs) >= 1 assert len(mux_configs[0]['registers']) > 1 # > 1 registers return mux_configs def add_register_config(set, priority, availability, regs, type): reg_config = et.SubElement(set, 'register_config') reg_config.set('type', type) if availability != None: assert type == "NOA" reg_config.set('priority', str(priority)) reg_config.set('availability', availability) for reg in regs: elem = et.SubElement(reg_config, 'register') elem.set('type', type) elem.set('address', "0x%08X" % reg[0]) elem.set('value', "0x%08X" % reg[1]) def to_text(value): if value == None: return "" return value # There are duplicated metric sets with the same symbol name so we # keep track of the sets we've read so we can skip duplicates... sets = {} guids = {} guids_xml = et.parse(args.guids) for guid in guids_xml.findall(".//guid"): hashing_key = oa_registry.Registry.chipset_derive_hash(guid.get('chipset'), guid.get('mdapi_config_hash')) guids[hashing_key] = guid.get('id') for arg in args.xml: mdapi = et.parse(arg) concurrent_group = mdapi.find(".//ConcurrentGroup") for mdapi_set in mdapi.findall(".//MetricSet"): apis = mdapi_set.get('SupportedAPI') if "OGL" not in apis and "OCL" not in apis and "MEDIA" not in apis: continue set_symbol_name = mdapi_set.get('SymbolName') if set_symbol_name in sets: print_err("WARNING: duplicate set named \"" + set_symbol_name + "\" (SKIPPING)") continue chipset = mdapi_set.get('SupportedHW') if concurrent_group.get('SupportedGT') != None: chipset = chipset + concurrent_group.get('SupportedGT') if chipset not in chipsets: print_err("WARNING: unsupported chipset {0}, consider updating {1}".format(chipset, __file__)) continue if args.whitelist: set_whitelist = args.whitelist.split() if set_symbol_name not in set_whitelist: continue if args.blacklist: set_blacklist = args.blacklist.split() else: set_blacklist = default_set_blacklist if set_symbol_name in set_blacklist: continue if mdapi_set.get('SnapshotReportSize') != '256': print_err("WARNING: skipping metric set '{0}', report size {1} invalid".format(set_symbol_name, mdapi_set.get('SnapshotReportSize'))) continue set = et.SubElement(metrics, 'set') set.set('chipset', chipset) set.set('name', mdapi_set.get('ShortName')) set.set('symbol_name', set_symbol_name) set.set('underscore_name', underscore(mdapi_set.get('SymbolName'))) set.set('mdapi_supported_apis', strip_dx_apis(mdapi_set.get('SupportedAPI'))) # Look at the hardware register config before looking at the counters. # # The hardware configuration is used as a key to lookup up a GUID which # is used by applications to lookup the corresponding counter # normalization equations. # # We want to skip over any metric sets that don't yet have a registered # GUID in guids.xml. # There can be multiple NOA MUX configs, since they may have associated # availability tests to match particular systems. # # Unlike the MDAPI XML files we only support tracking one group of # mutually exclusive MUX configs, whereas the MDAPI XML files # theoretically allow a single metric set to be associated with ordered # groups of mutually exclusive configs. So far there is only one # Broadwell, ComputeExtended metric set which uses this, but that # particular case can be expressed in less general terms. # # Being a bit simpler here should make it easier for downstream tools # to deal with. (At least we got the handling of the Broadwell # ComputeExtended example wrong and it took several email exchanges and # a conference call to confirm how to interpret this case) mux_configs = process_mux_configs(mdapi_set) # Unlike for MUX registers, we only expect one set of FLEX/OA # registers per metric set (even though they are sometimes duplicated # between configs in MDAPI XML files. # # This filter function, extracts the register of a certain type but # also double checks that if they are repeated in separate configs that # they don't vary. (Notably the current i915 perf Linux driver would # need some adapting to support multiple OA/FLEX configs with different # availability expressions) # flex_regs = filter_single_config_registers_of_type(mdapi_set, "FLEX") oa_regs = filter_single_config_registers_of_type(mdapi_set, "OA") # Note: we ignore Perfmon registers for mux_config in mux_configs: add_register_config(set, mux_config['priority'], mux_config['availability'], mux_config['registers'], "NOA") if len(oa_regs) > 0: add_register_config(set, 0, None, oa_regs, "OA") if len(flex_regs) > 0: add_register_config(set, 0, None, flex_regs, "FLEX") mdapi_hw_config_hash = oa_registry.Registry.mdapi_hw_config_hash(mdapi_set) guid_hash = oa_registry.Registry.chipset_derive_hash(chipset.lower(), mdapi_hw_config_hash) hw_config_hash = oa_registry.Registry.hw_config_hash(set) if guid_hash in guids: set.set('hw_config_guid', guids[guid_hash]) else: print_err("WARNING: No GUID found for metric set " + chipset + ", " + set_symbol_name + " (SKIPPING)") print_err("WARNING: If this is a new config add the following to guids.xml:") print_err("") metrics.remove(set) continue sets[set_symbol_name] = set counters = {} normalization_equations = {} raw_equations = {} # Awkwardly we can't assume metrics are in dependency order and have to # sort them manually. We start by associating a list of dependencies with # each counter... mdapi_counters = {} mdapi_counter_deps = {} for mdapi_counter in mdapi_set.findall("Metrics/Metric"): symbol_name = mdapi_counter.get('SymbolName') if symbol_name in counter_blacklist: continue; # Have seen at least one MetricSet with a duplicate GpuCoreClocks counter... if symbol_name in mdapi_counters: print_err("WARNING: Skipping duplicate counter \"" + symbol_name + \ "\" in " + set.get('name') + " :: " + mdapi_counter.get('ShortName')) continue; deps = [] equations = fixup_equation(str(mdapi_counter.get('SnapshotReportReadEquation'))) + " " + \ fixup_equation(str(mdapi_counter.get('SnapshotReportDeltaEquation'))) + " " + \ fixup_equation(str(mdapi_counter.get('DeltaReportReadEquation'))) + " " + \ fixup_equation(str(mdapi_counter.get('NormalizationEquation'))) equations = expand_macros(equations) equations = equations.replace('$$', "$") for token in equations.split(): if token[0] == '$' and token[1:] not in sys_vars and token[1:] != "Self": deps.append(token[1:]) mdapi_counters[symbol_name] = mdapi_counter mdapi_counter_deps[symbol_name] = deps sorted_mdapi_counters = sort_counters(mdapi_counters, mdapi_counter_deps) for mdapi_counter in sorted_mdapi_counters: aliases = mdapi_counter.get('Alias') skip_counter = False # We don't currently support configuring and reading perfmon registers signal = mdapi_counter.get('SignalName') if signal and "perfmon" in signal: continue; # A few things to fixup with this common counter... if mdapi_counter.get('SymbolName') == "AvgGpuCoreFrequencyMHz": # To avoid requiring a special case in tools, add a max value # equation for the gpu frequency... mdapi_counter.set('MaxValueEquation', "$GpuMaxFrequency") # Don't include units in the name mdapi_counter.set('SymbolName', "AvgGpuCoreFrequency") # Use canonical, first order of magnitude units specifier mdapi_counter.set('MetricUnits', 'Hz') mdapi_counter.set('NormalizationEquation', '$GpuCoreClocks 1000000000 UMUL $GpuTime UDIV') #mdapi_counter.set('DeltaReportReadEquation', '$GpuCoreClocks $GpuTime UDIV') symbol_name = mdapi_counter.get('SymbolName') counter = et.SubElement(set, 'counter') counter.set('name', apply_aliases(mdapi_counter.get('ShortName'), aliases)) counter.set('symbol_name', mdapi_counter.get('SymbolName')) counter.set('underscore_name', underscore(mdapi_counter.get('SymbolName'))) counter.set('description', apply_aliases(mdapi_counter.get('LongName'), aliases)) counter.set('mdapi_group', apply_aliases(to_text(mdapi_counter.get('Group')), aliases)) counter.set('mdapi_usage_flags', to_text(mdapi_counter.get('UsageFlags'))) counter.set('mdapi_supported_apis', strip_dx_apis(mdapi_counter.get('SupportedAPI'))) low = mdapi_counter.get('LowWatermark') if low: counter.set('low_watermark', low) high = to_text(mdapi_counter.get('HighWatermark')) if high: counter.set('high_watermark', high) counter.set('data_type', mdapi_counter.get('ResultType').lower()) max_eq = fixup_equation(mdapi_counter.get('MaxValueEquation')) if max_eq: counter.set('max_equation', max_eq) # XXX Not sure why EU metrics tend to just be bundled under 'gpu' counter.set('mdapi_hw_unit_type', mdapi_counter.get('HWUnitType').lower()) # There are counters representing cycle counts that have a semantic # type of 'duration' which doesn't seem to make sense... units = mdapi_counter.get('MetricUnits').lower() if units == "cycles": semantic_type = "event" else: semantic_type = mdapi_counter.get('MetricType').lower() counter.set('units', units) counter.set('semantic_type', semantic_type) # MDAPI MetricSets have 3 different kinds of counter read equations: # # 1) One for reading a raw (unnormalized) value from a hardware report # # The line between normalized and raw isn't always clear # as the raw equation may e.g. read and ADD multiple counters # # Not all counters have a raw equation if they are instead # derived through $CounterName references to other counters # in a normalized value equation # # 2) One for reading an unnormalized value from the accumulated 'delta reports' # # Seems to duplicate the raw equation but with delta report # offsets and referencing 64bit values # # The normalized value equations are always based on these # accumulated delta values # # 3) One for reading a normalized value # # These may start with a reference to "$Self" which is # effectively a macro for the above delta report equation # # If this is missing the delta report equation is effectively # the normalized equation too # # XXX: Beware that there are some inconsistent counters that # have a normalization equation with a $Self reference and a # raw equation but no delta report equation. This seems # pretty sketchy, but (at least for 'MEDIA' metrics) we will # substitute the raw equation for $Self in this case along # with a warning to double check the results. # # Currently there doesn't appear to be a clear reason to # differentiate these equations and the separation seems to # complicate things for tools wanting to generate code from this # data. # # We instead aim to have one normalized equation per counter that # always reference accumulated counter values. # XXX: As a special case, we override the raw and delta report # equations for the GpuTime counters, which seem inconsistent if mdapi_counter.get('SymbolName') == "GpuTime": mdapi_counter.set('SnapshotReportReadEquation', "dw@0x04 1000000000 UMUL $GpuTimestampFrequency UDIV") mdapi_counter.set('DeltaReportReadEquation', "qw@0x0 1000000000 UMUL $GpuTimestampFrequency UDIV") availability = fixup_equation(mdapi_counter.get('AvailabilityEquation')) if availability == "": availability = None # We prefer to only look at the equations that reference the raw # reports since the mapping of offsets back to A,B,C counters is # unambiguous, but if necessary we will fallback to mapping # delta report offsets (accumulated 64bit values that correspond # to the 32bit or 40bit values from raw repots) raw_read_eq = fixup_equation(mdapi_counter.get('SnapshotReportReadEquation')) if raw_read_eq: if raw_read_eq == "": raw_read_eq = None else: raw_read_eq = replace_read_tokens_with_rpn_read_ops(chipset, raw_read_eq, True) #raw offsets delta_read_eq = fixup_equation(mdapi_counter.get('DeltaReportReadEquation')) if delta_read_eq: if delta_read_eq == "": delta_read_eq = None else: delta_read_eq = replace_read_tokens_with_rpn_read_ops(chipset, delta_read_eq, False) #delta offsets if raw_read_eq and not delta_read_eq: print_err("WARNING: Counter with raw equation but no delta report equation: MetricSet=\"" + \ mdapi_set.get('ShortName') + "\" Metric=\"" + mdapi_counter.get('SymbolName') + \ "(" + mdapi_counter.get('ShortName') + ")" + "\"") # Media metric counters currently have no delta equation even # though they have normalization equations that reference $Self if "MEDIA" in apis: print_err("WARNING: -> Treating inconsistent media metric's 'raw' equation as a 'delta report' equation, but results should be double checked!") delta_read_eq = raw_read_eq else: set.remove(counter) continue # Some counters are sourced from register values that are # not put into the OA reports. This is why some counters # will have a delta equation but not a raw equation. These # counters are typically only available in query mode. For # this reason we put a particular availability value. if delta_read_eq and not raw_read_eq: assert availability == None availability = "true $QueryMode &&" raw_read_eq = delta_read_eq # After replacing read tokens with RPN counter READ ops the raw and # delta equations are expected to be identical so warn if that's # not true... if bool(raw_read_eq) ^ bool(delta_read_eq) or raw_read_eq != delta_read_eq: print_err("WARNING: Inconsistent raw and delta report equations for " + \ mdapi_set.get('ShortName') + " :: " + mdapi_counter.get('SymbolName') + \ "(" + mdapi_counter.get('ShortName') + ")" + ": raw=\"" + str(raw_read_eq) + \ "\" delta=\"" + str(delta_read_eq) + "\" (SKIPPING)") set.remove(counter) continue normalize_eq = fixup_equation(mdapi_counter.get('NormalizationEquation')) if normalize_eq and normalize_eq == "": normalize_eq = None if normalize_eq: # Some normalization equations are represented with macros such as # 'GpuDuration' corresponding to: # # "$Self 100 UMUL $GpuCoreClocks FDIV" # # We expand macros here so tools don't need to care about them... # equation = normalize_eq equation = expand_macros(equation) if raw_read_eq: equation = equation.replace('$Self', raw_read_eq) else: equation = delta_read_eq if '$Self' in equation: print_err("WARNING: Counter equation (\"" + equation + "\") with unexpanded $Self token: MetricSet=\"" + \ mdapi_set.get('ShortName') + "\" Metric=\"" + mdapi_counter.get('SymbolName') + \ "(" + mdapi_counter.get('ShortName') + ")" + "\" (SKIPPING)") set.remove(counter) continue # $$CounterName vs $CounterName in an equation is intended to # differentiate referencing the normalized or raw value of another # counter. # # Since we are only keeping a single (normalized) equation for # counters we only need one form, but we want to be careful to # check if any equations really depend on the raw value of another # counter so we can expand those variables now # tmp = equation for token in tmp.split(): if token[0] == '$' and token[1] != '$': if token[1:] in normalization_equations: raw_eq = raw_equations[token[1:]] equation = equation.replace(token, raw_eq) #if token[1:] not in raw_equations: # print_err("WARNING: Counter equation (\"" + equation + "\") references un-kept raw equation of another counter : MetricSet=\"" + \ # mdapi_set.get('ShortName') + "\" Metric=\"" + mdapi_counter.get('ShortName') + "\"") elif token[1:] not in raw_equations and token[1:] not in sys_vars: print_err("Unknown variable name: \"" + token + "\" in equation \"" + equation + "\"") symbol_name = counter.get('symbol_name') # Make sure that every variable in the equation is a known sys_var or counter name equation = equation.replace('$$', "$") for token in equation.split(): if token[0] == '$': if token[1:] not in counters and token[1:] not in sys_vars: print_err("WARNING: Counter equation (\"" + equation + "\") with unknown variable " + \ token + " (maybe skipped counter): MetricSet=\"" + mdapi_set.get('ShortName') + \ "\" Metric=\"" + mdapi_counter.get('SymbolName') + "(" + mdapi_counter.get('ShortName') + \ ")" + "\" (SKIPPING)") set.remove(counter) skip_counter = True break if skip_counter: continue counter.set('equation', equation.strip()) if availability != None: counter.set('availability', availability) counters[symbol_name] = counter; if normalize_eq: normalization_equations[symbol_name] = normalize_eq if raw_read_eq: raw_equations[symbol_name] = raw_read_eq if args.dry_run: sys.exit(0) # Merge in any custom meta data we have... if args.merge: merge = et.parse(args.merge) merge_metrics = merge.getroot() for merge_set in merge.findall(".//set"): pattern = ".//set[@symbol_name=\"" + merge_set.get('symbol_name') + "\"][@chipset=\"" + merge_set.get('chipset') + "\"]" real_set = metrics.find(pattern) if real_set is not None: for set_attr in merge_set.items(): real_set.set(set_attr[0], set_attr[1]) for merge_elem in merge_set: if merge_elem.tag == "counter": merge_counter = merge_elem pattern = "counter[@symbol_name=\"" + merge_counter.get('symbol_name') + "\"]" real_counter = real_set.find(pattern) if real_counter is not None: for counter_attr in merge_counter.items(): real_counter.set(counter_attr[0], counter_attr[1]) else: real_set.append(merge_counter) real_counter = merge_counter else: real_set.append(merge_elem) # For consistency + readability print everything manually... merge_md5 = hashlib.md5(open("merge.xml", 'rb').read()).hexdigest() else: merge_md5 = "" print ("") print("") for set in metrics.findall(".//set"): print(" ") for counter in set.findall("counter"): print(" ") for config in set.findall("register_config"): if config.get('availability') != None: print(" ") else: print(" ") for reg in config.findall("register"): addr = int(reg.get('address'), 16) if 'registers' in chipsets[chipset] and addr in chipsets[chipset]['registers']: reg_info = chipsets[chipset]['registers'][addr] comment = ' ' else: comment = '' print(" " + comment) print(" ") print(" \n") print("") ================================================ FILE: scripts/meson-cross/emscripten-docker-debug.txt ================================================ [binaries] c = '/opt/emsdk-portable/emscripten/1.37.27/emcc' cpp = '/opt/emsdk-portable/emscripten/1.37.27/em++' ar = '/opt/emsdk-portable/emscripten/1.37.27/emar' #exe_wrapper = 'node' [properties] root = '/opt/emsdk-portable/emscripten/1.37.27/system' c_args = ['-s', 'WASM=1', '-O2', '-s', 'FULL_ES2=1', '-g4', '-s', 'USE_SDL=2', '-s', 'ASSERTIONS=1', '-s', 'DEMANGLE_SUPPORT=1'] c_link_args = ['-s', 'WASM=1','-O2', '-s', 'FULL_ES2=1', '--emit-symbol-map', '-g4', '-s', 'USE_SDL=2', '-s', 'ASSERTIONS=1', '-s', 'DEMANGLE_SUPPORT=1', '-s', 'TOTAL_MEMORY=96MB'] cpp_args = ['-s', 'WASM=1','-O2', '-s', 'FULL_ES2=1', '-g4', '-s', 'USE_SDL=2', '-s', 'ASSERTIONS=1', '-s', 'DEMANGLE_SUPPORT=1'] cpp_link_args = ['-s', 'WASM=1','-O2', '-s', 'FULL_ES2=1', '--emit-symbol-map', '-g4', '-s', 'USE_SDL=2', '-s', 'ASSERTIONS=1', '-s', 'DEMANGLE_SUPPORT=1', '-s', 'TOTAL_MEMORY=96MB'] [host_machine] system = 'emscripten' cpu_family = 'x86' cpu = 'i686' endian = 'little' ================================================ FILE: scripts/meson-cross/emscripten-docker-release.txt ================================================ [binaries] c = '/opt/emsdk-portable/emscripten/1.37.27/emcc' cpp = '/opt/emsdk-portable/emscripten/1.37.27/em++' ar = '/opt/emsdk-portable/emscripten/1.37.27/emar' #exe_wrapper = 'node' [properties] root = '/opt/emsdk-portable/emscripten/1.37.27/system' c_args = ['-s', 'WASM=1', '-O2', '-s', 'FULL_ES2=1', '-s', 'USE_SDL=2'] c_link_args = ['-s', 'WASM=1','-O2', '-s', 'FULL_ES2=1', '-s', 'USE_SDL=2', '-s', 'TOTAL_MEMORY=96MB'] cpp_args = ['-s', 'WASM=1','-O2', '-s', 'FULL_ES2=1', '-s', 'USE_SDL=2'] cpp_link_args = ['-s', 'WASM=1','-O2', '-s', 'FULL_ES2=1', '-s', 'USE_SDL=2', '-s', 'TOTAL_MEMORY=96MB'] [host_machine] system = 'emscripten' cpu_family = 'x86' cpu = 'i686' endian = 'little' ================================================ FILE: scripts/pylibs/.gitignore ================================================ **__init__.pyc ================================================ FILE: scripts/pylibs/__init__.py ================================================ ================================================ FILE: scripts/pylibs/codegen/__init__.py ================================================ class Codegen: _file = None _indent = 0 endl="\n" use_tabs = False def __init__(self, filename = None): if filename != None: self._file = open(filename, 'w') def __call__(self, *args): if self._file: code = ' '.join(map(str, args)) for line in code.splitlines(): indent = ''.rjust(self._indent) if self.use_tabs: indent = indent.replace(" ", "\t") text = indent + line self._file.write(text.rstrip() + self.endl) #without indenting or new lines def frag(self, *args): code = ' '.join(map(str, args)) self._file.write(code) def indent(self, n): self._indent = self._indent + n def outdent(self, n): self._indent = self._indent - n ================================================ FILE: scripts/pylibs/oa_guid_registry/__init__.py ================================================ import copy import hashlib import xml.etree.ElementTree as et class Registry: # Tries to avoid fragility from et.tostring() by normalizing into CSV string first @staticmethod def hw_config_hash(metric_set): """Hashes the given metric set's HW register configs. Args: metric_set -- is an ElementTree element for a 'set' Note this doesn't accept an MDAPI based metric set description """ registers_str = "" for config in metric_set.findall(".//register_config"): if config.get('id') == None: config_id = '0' else: config_id = config.get('id') if config.get('priority') == None: config_priority = '0' else: config_priority = config.get('priority') if config.get('availability') == None: config_availability = "" else: config_availability = config.get('availability') for reg in config.findall("register"): addr = int(reg.get('address'), 16) value = int(reg.get('value'), 16) registers_str = registers_str + config_id + ',' + config_priority + ',' + config_availability + ',' + str(addr) + ',' + str(value) + '\n' return hashlib.md5(registers_str.encode('utf-8')).hexdigest() @staticmethod def mdapi_hw_config_hash(mdapi_metric_set): """Hashes the HW register configuration of a metric set from VPG's MDAPI XML files. Args: mdapi_metric_set -- is an ElementTree element for a 'MetricSet' Note: being a simplistic hash of all RegConfigStart element contents this will change for minor comment changes in VPG's files. Without any promisies of stability within these files then it can't help to err on the side of caution here, so we know when to investigate changes that might affect our useages. """ config = et.Element('config') for registers in mdapi_metric_set.findall(".//RegConfigStart"): config.append(copy.deepcopy(registers)) registers_str = et.tostring(config) return hashlib.md5(registers_str).hexdigest() @staticmethod def chipset_derive_hash(chipset, hash): """Derive a HW config hash for a given chipset. This helps us avoiding collisions with identical config across different Gen or GT. """ return "%s-%s" % (chipset, hash) ================================================ FILE: scripts/travis-ci-build.sh ================================================ #!/bin/bash set -e set -x LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_ALL=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 export LANG LANGUAGE LC_ALL if test -z "$TRAVIS_BUILD_DIR"; then TRAVIS_BUILD_DIR=$PWD fi gcc --version g++ --version # When the emscripten SDK is installed, we don't install the node and # instead use the one from the SDK. if [ -d /opt/emsdk-portable ]; then export PATH="/opt/emsdk-portable/clang/e1.37.27_64bit:/opt/emsdk-portable/node/4.1.1_64bit/bin:/opt/emsdk-portable/emscripten/1.37.27:$PATH" emcc -v fi # Fetch glext.h header including INTEL_performance_query enums #$(mkdir GL && cd GL && wget https://raw.githubusercontent.com/rib/mesa/wip/rib/oa-next/include/GL/glext.h) meson --version if [ -d travis-build ]; then rm -rf travis-build fi meson travis-build . $CONFIG_OPTS --prefix=$TRAVIS_BUILD_DIR/travis-install --default-library=static ninja -v -C travis-build ninja -v -C travis-build install ================================================ FILE: scripts/travis-ci-prep-docker-centos.sh ================================================ #!/bin/sh set -e if ! test $# -eq 2; then echo "usage: $0 docker-base-image-name new-image-name" exit 1 fi _USER=`id -un` _UID=`id -u` _GID=`id -g` _GROUP=`id -gn` if test $_UID -eq 0; then echo "Not expected to be run as root" echo "" echo "This script should be run as the user that will" echo "be building gputop" exit 1 fi cat << EOF > Dockerfile FROM $1 USER root RUN yum clean all RUN yum update -y && yum install -y \ make \ sudo \ pkg-config \ gettext \ python34-pip \ python34-setuptools \ python-lxml \ python-mako \ ncurses-devel \ mesa-libGL-devel \ openssl-devel \ glfw-devel \ libepoxy-devel \ mesa-libEGL-devel \ ninja-build \ curl \ psmisc \ unzip \ which && \ yum clean all RUN curl -sL https://rpm.nodesource.com/setup_6.x | sudo -E bash - && \ yum install -y nodejs && \ yum clean all RUN ln -sf /usr/bin/ninja-build /usr/bin/ninja RUN easy_install-3.4 pip RUN pip3 install meson==0.44.0 RUN groupadd -g $_GID $_GROUP && useradd -u $_UID -g $_GID -G wheel -m $_USER RUN echo "%sudo ALL=NOPASSWD: ALL">>/etc/sudoers USER $_USER RUN touch /home/$_USER/.sudo_as_admin_successfull RUN mkdir /home/$_USER/build WORKDIR /home/$_USER/build CMD ["/bin/bash"] EOF echo "Deriving final $2 build image from base $1 image..." echo "" echo " This is adding a '$_USER' user that matches the current host user" echo " to allow seamless mounting of host directories" echo "" docker build -t $2 . cat << EOF > build.sh sudo docker run -t -i -v \$PWD:/home/$USER/src $2 build/scripts/travis-ci-build.sh EOF chmod +x ./build.sh echo "" echo "Ready!" echo "" echo "To enter the build environment run:" echo "" echo "$ sudo docker run -t -i -v \$PWD:/home/$USER/build $2" echo "" echo "This will mount the host's current working directory in ~/build" echo "" ================================================ FILE: scripts/travis-ci-prep-docker-ubuntu.sh ================================================ #!/bin/sh set -e if ! test $# -eq 2; then echo "usage: $0 docker-base-image-name new-image-name" exit 1 fi _USER=`id -un` _UID=`id -u` _GID=`id -g` _GROUP=`id -gn` if test $_UID -eq 0; then echo "Not expected to be run as root" echo "" echo "This script should be run as the user that will" echo "be building gputop" exit 1 fi cat << EOF > Dockerfile FROM $1 USER root RUN apt-get update -y && apt-get install -y --no-install-recommends --no-install-suggests \ sudo \ pkg-config \ gettext \ python3-pip \ python3-setuptools \ python-lxml \ libncursesw5-dev \ libgl1-mesa-dev \ libssl-dev \ libglfw3-dev \ libepoxy-dev \ libegl1-mesa-dev \ curl \ psmisc \ unzip && \ apt-get clean RUN pip3 install meson==0.44.0 RUN groupadd -g $_GID $_GROUP && useradd -u $_UID -g $_GID -G sudo -m $_USER RUN echo "%sudo ALL=NOPASSWD: ALL">>/etc/sudoers USER $_USER RUN touch /home/$_USER/.sudo_as_admin_successfull RUN mkdir /home/$_USER/build WORKDIR /home/$_USER/build CMD ["/bin/bash"] EOF echo "Deriving final $2 build image from base $1 image..." echo "" echo " This is adding a '$_USER' user that matches the current host user" echo " to allow seamless mounting of host directories" echo "" docker build -t $2 . cat << EOF > build.sh sudo docker run -t -i -v \$PWD:/home/$USER/src $2 build/scripts/travis-ci-build.sh EOF chmod +x ./build.sh echo "" echo "Ready!" echo "" echo "To enter the build environment run:" echo "" echo "$ sudo docker run -t -i -v \$PWD:/home/$USER/build $2" echo "" echo "This will mount the host's current working directory in ~/build" echo "" ================================================ FILE: scripts/travis-ci-test.sh ================================================ #!/bin/bash set -x LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_ALL=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 export LANG LANGUAGE LC_ALL if test -z "$TRAVIS_BUILD_DIR"; then TRAVIS_BUILD_DIR=$PWD fi #export GPUTOP_TRAVIS_MODE=1 export PATH=$TRAVIS_BUILD_DIR/travis-install/bin:$PATH if [ "${CONFIG_OPTS/'webui=true'}" == "$CONFIG_OPTS" ]; then gputop --fake 2> travis_log & GPUTOP_PID=$! sleep 3 gputop-wrapper -m RenderBasic -c "Timestamp,GpuCoreClocks" & GPUTOP_WRAPPER_PID=$! sleep 10 kill $GPUTOP_WRAPPER_PID kill $GPUTOP_PID echo "Server Log:" cat travis_log grep -q "OpenStream request received" travis_log || exit 1 fi #TODO: test web ui echo "PASSED" exit 0 ================================================ FILE: scripts/update-guids.py ================================================ #!/usr/bin/env python2 # coding=utf-8 # Copyright (C) 2016 Intel Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # This script can: # # - Automatically add template entries for unregistered metric sets diescovered # in new mdapi xml files. # - Once mdapi-convert-xml.py has been run to output register configs for new # metric sets then re-running this script can add the config_hash attribute # to corresponding registry entries. # # The script is designed to allow incremental updates/fixups of the guid # registry by working in terms of: # # 1) load all the existing state # 2) apply tweaks/modifications # 3) write everything back out # # The script should gracefully handle incomplete guid entries, which is # important when considering how the mdapi-xml-convert.py script depends on the # 'mdapi_config_hash' attribute while adding the 'config_hash' attribute # depends on the configs output by mdapi-xml-convert.py. import argparse import os.path import re import sys import time import uuid import xml.etree.ElementTree as et import xml.sax.saxutils as saxutils import pylibs.oa_guid_registry as oa_registry def print_err(*args): sys.stderr.write(' '.join(map(str,args)) + '\n') def guid_hashing_key(guid_obj): return oa_registry.Registry.chipset_derive_hash(guid_obj['chipset'], guid_obj['mdapi_config_hash']) parser = argparse.ArgumentParser() parser.add_argument("xml", nargs="+", help="XML description of metrics") parser.add_argument("--guids", required=True, help="Metric set GUID registry") args = parser.parse_args() guids = [] guid_index = {} # guid objects indexed by id mdapi_config_hash_guid_table = {} # indexed by MDAPI XML register config hash named_guid_table = {} # indexed by name=_ # 1) read everything we have currently # guids_xml = et.parse(args.guids) for guid in guids_xml.findall(".//guid"): guid_obj = {} if guid.get('id') != None: guid_obj['id'] = guid.get('id') else: guid_obj['id'] = str(uuid.uuid4()) if guid.get('mdapi_config_hash') != None: guid_obj['mdapi_config_hash'] = guid.get('mdapi_config_hash') if guid.get('config_hash') != None: guid_obj['config_hash'] = guid.get('config_hash') if guid.get('chipset') != None: guid_obj['chipset'] = guid.get('chipset') if guid.get('name') != None: guid_obj['name'] = guid.get('name') named_guid_table[guid_obj['chipset'] + "_" + guid_obj['name']] = guid_obj if 'mdapi_config_hash' in guid_obj: hashing_key = oa_registry.Registry.chipset_derive_hash(guid_obj['chipset'], guid_obj['mdapi_config_hash']) mdapi_config_hash_guid_table[hashing_key] = guid_obj guids.append(guid_obj) if guid_obj['id'] in guid_index: print_err("Duplicate GUID " + guid_obj['id'] + "!") sys.exit(1) guid_index[guid_obj['id']] = guid_obj # # 2) fixup/modify the guid entries... # for arg in args.xml: internal = et.parse(arg) concurrent_group = internal.find(".//ConcurrentGroup") for mdapi_set in internal.findall(".//MetricSet"): mdapi_config_hash = oa_registry.Registry.mdapi_hw_config_hash(mdapi_set) chipset = mdapi_set.get('SupportedHW').lower() if concurrent_group.get('SupportedGT') != None: chipset = chipset + concurrent_group.get('SupportedGT').lower() set_name = mdapi_set.get('SymbolName') name = chipset + "_" + set_name; hashing_key = oa_registry.Registry.chipset_derive_hash(chipset, mdapi_config_hash) if hashing_key in mdapi_config_hash_guid_table: guid_obj = mdapi_config_hash_guid_table[hashing_key] guid_obj['name'] = set_name guid_obj['chipset'] = chipset guid_obj['matched_mdapi'] = True elif name in named_guid_table: guid_obj = named_guid_table[name] guid_obj['matched_mdapi'] = True guid_obj['mdapi_config_hash'] = mdapi_config_hash if 'config_hash' in guid_obj: del guid_obj['config_hash'] guid_obj['comment'] = "WARNING: MDAPI XML config hash changed! If upstream, double check raw counter semantics unchanged" print_err("WARNING: MDAPI XML config hash changed for \"" + set_name + "\" (" + chipset + ") If upstream, double check raw counter semantics unchanged") else: guid_obj = { 'mdapi_config_hash': mdapi_config_hash, 'id': str(uuid.uuid4()), 'name': set_name, 'chipset': chipset, 'unregistered': True, 'matched_mdapi': True, 'comment': "New" } guid_index[guid_obj['id']] = guid_obj mdapi_config_hash_guid_table[guid_hashing_key(guid_obj)] = guid_obj guids.append(guid_obj) print_err("New GUID \"" + guid_obj['id'] + "\" for metric set = " + set_name + " (" + chipset + ")") named_guid_table[chipset + '_' + set_name] = guid_obj chipsets = [ 'hsw', 'bdw', 'chv', 'sklgt2', 'sklgt3', 'sklgt4', 'kblgt2', 'kblgt3', 'cflgt2', 'cflgt3', 'bxt', 'glk', 'cnl', 'icl', 'lkf', 'tgl'] for chipset in chipsets: filename = 'oa-' + chipset + '.xml' if not os.path.isfile(filename): continue public = et.parse(filename) for metricset in public.findall(".//set"): set_name = metricset.get('symbol_name') config_hash = oa_registry.Registry.hw_config_hash(metricset) guid_key = chipset + "_" + set_name if guid_key in named_guid_table: guid_obj = named_guid_table[guid_key] guid_obj['config_hash'] = config_hash # # 3) write all the guids back out... print("") for guid_obj in guids: comment = None line = "' if comment != None: print(" ") print(" " + line) print("") ================================================ FILE: server/gputop-cpu.c ================================================ /* * GPU Top * * Copyright (C) 2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include "gputop-util.h" #include "gputop-sysutil.h" #include "gputop-log.h" #include "gputop-cpu.h" static pthread_once_t count_once = PTHREAD_ONCE_INIT; static int n_cpus = 0; static void count_cpus(void) { char buf[32]; unsigned ignore = 0, max_cpu = 0; if (!gputop_read_file("/sys/devices/system/cpu/present", buf, sizeof(buf))) return; if (sscanf(buf, "%u-%u", &ignore, &max_cpu) != 2) return; n_cpus = max_cpu + 1; } int gputop_cpu_count(void) { if (n_cpus) return n_cpus; pthread_once(&count_once, count_cpus); return n_cpus; } bool gputop_cpu_model(char *buf, int len) { FILE *fp; char *line = NULL; size_t line_len = 0; ssize_t read; const char *key = "model name\t: "; int key_len = strlen(key); memset(buf, 0, len); snprintf(buf, len, "Unknown"); fp = fopen("/proc/cpuinfo", "r"); if (!fp) return false; while ((read = getline(&line, &line_len, fp)) != -1) { if (strncmp(key, line, key_len) == 0) { snprintf(buf, len, "%s", line + key_len); fclose(fp); free(line); return true; } } fclose(fp); free(line); return false; } bool gputop_cpu_read_stats(struct cpu_stat *stats, int n_cpus) { FILE *fp = fopen("/proc/stat", "r"); char *line = NULL; size_t line_len = 0; uint64_t timestamp = gputop_get_time(); int n_read = 0; if (!fp) { dbg("Failed to open /proc/stat\n"); return false; } while (getline(&line, &line_len, fp) > 0) { struct cpu_stat st = { 0 }; int ret = sscanf(line, "cpu%u %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu", &st.cpu, &st.user, &st.nice, &st.system, &st.idle, &st.iowait, &st.irq, &st.softirq, &st.steal, &st.guest, &st.guest_nice); if (ret == 11) { if (st.cpu >= n_cpus) { dbg("cpu stats buffer too small\n"); break; } st.timestamp = timestamp; stats[st.cpu] = st; n_read++; } } free(line); fclose(fp); if (n_read != n_cpus) { dbg("Failed to read all cpu stats\n"); return false; } return true; } ================================================ FILE: server/gputop-cpu.h ================================================ /* * GPU Top * * Copyright (C) 2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once struct cpu_stat { uint64_t timestamp; unsigned cpu; unsigned long user; unsigned long nice; unsigned long system; unsigned long idle; unsigned long iowait; unsigned long irq; unsigned long softirq; unsigned long steal; unsigned long guest; unsigned long guest_nice; }; int gputop_cpu_count(void); bool gputop_cpu_model(char *buf, int len); bool gputop_cpu_read_stats(struct cpu_stat *stats, int n_cpus); ================================================ FILE: server/gputop-debugfs.c ================================================ /* * GPU Top * * Copyright (C) 2016 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include "gputop-debugfs.h" #include "gputop-util.h" #include "gputop-sysutil.h" static const char *debugfs_path = "/sys/kernel/debug"; static bool debugfs_mounted; static bool debugfs_mount(void) { struct stat st; if (debugfs_mounted) return true; if (stat("/sys/kernel/debug/dri", &st) == 0) { debugfs_mounted = true; return true; } if (mount("debug", debugfs_path, "debugfs", 0, 0) == 0) { debugfs_mounted = true; return true; } fprintf(stderr, "Failed to mount debugfs\n"); return false; } int gputop_debugfs_open(const char *filename, int mode) { char buf[1024]; if (!debugfs_mount()) return -1; snprintf(buf, sizeof(buf), "%s/%s", debugfs_path, filename); return open(buf, mode); } FILE *gputop_debugfs_fopen(const char *filename, const char *mode) { char buf[1024]; if (!debugfs_mount()) return NULL; snprintf(buf, sizeof(buf), "%s/%s", debugfs_path, filename); return fopen(buf, mode); } /* Returns entire file contents as a NUL terminated string * returned len doesnt count the added NUL terminator. * * NB: free() when done. */ void *gputop_debugfs_read(const char *filename, int *len) { FILE *file; size_t size = 0; char *contents = NULL; int r = 0; int offset = 0; file = gputop_debugfs_fopen(filename, "r"); if (!file) { fprintf(stderr, "Failed to open %s: %m\n", filename); return NULL; } do { size += 4096; contents = xrealloc(contents, size); r = fread(contents + offset, 1, 4096, file); offset += r; } while (r == 4096); contents[offset] = '\0'; fclose(file); return contents; } uint64_t gputop_debugfs_read_uint64(const char *filename) { char buf[1024]; uint64_t value; if (!debugfs_mount()) { return 0; } snprintf(buf, sizeof(buf), "%s/%s", debugfs_path, filename); if (!gputop_read_file_uint64(buf, &value)) return 0; return value; } char ** gputop_debugfs_get_tracepoint_names(void) { FILE *fp; char *line = NULL; size_t line_len = 0; ssize_t read; int n = 0; int i = 0; char **vec; fp = gputop_debugfs_fopen("tracing/available_events", "r"); if (!fp) return NULL; for (n = 0; (read = getline(&line, &line_len, fp)) != -1; n++) ; if (n == 0) return NULL; vec = xmalloc0(sizeof(char *) * (n + 1)); fseek(fp, 0, SEEK_SET); while ((read = getline(&line, &line_len, fp)) != -1) { int len = strlen(line); char *delim; if (line[len - 1] == '\n') line[len - 1] = '\0'; delim = strstr(line, ":"); if (!delim) { fprintf(stderr, "spurious line format in available_events '%s'\n", line); continue; } *delim = '/'; vec[i++] = strdup(line); } vec[i++] = NULL; fclose(fp); free(line); return vec; } void gputop_debugfs_free_tracepoint_names(char **names) { if (!names) return; for (int i = 0; names[i]; i++) free(names[i]); free(names); } char ** gputop_get_events_names(void) { DIR *devices_dir; struct dirent *device_entry; char **names; int max_names = 100; int n_names = 0; names = xmalloc0(sizeof(char *) * (max_names + 1)); devices_dir = opendir("/sys/devices"); assert(devices_dir != NULL); while ((device_entry = readdir(devices_dir))) { char device_path[1024]; DIR *device_dir; struct dirent *event_entry; if (device_entry->d_type != DT_DIR) continue; snprintf(device_path, sizeof(device_path), "/sys/devices/%s/events", device_entry->d_name); device_dir = opendir(device_path); if (!device_dir) continue; while ((event_entry = readdir(device_dir))) { char event_relative_path[1024]; if (strstr(event_entry->d_name, ".") != NULL) continue; if (n_names >= max_names) { max_names *= 2; names = xrealloc(names, sizeof(char *) * (max_names + 1)); } snprintf(event_relative_path, sizeof(event_relative_path), "%s/events/%s", device_entry->d_name, event_entry->d_name); names[n_names++] = strdup(event_relative_path); } closedir(device_dir); } closedir(devices_dir); return names; } void gputop_free_events_names(char **names) { if (!names) return; for (int i = 0; names[i]; i++) free(names[i]); free(names); } ================================================ FILE: server/gputop-debugfs.h ================================================ /* * GPU Top * * Copyright (C) 2016 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once int gputop_debugfs_open(const char *filename, int mode); FILE *gputop_debugfs_fopen(const char *filename, const char *mode); void *gputop_debugfs_read(const char *filename, int *len); uint64_t gputop_debugfs_read_uint64(const char *filename); char ** gputop_debugfs_get_tracepoint_names(void); void gputop_debugfs_free_tracepoint_names(char **names); char ** gputop_get_events_names(void); void gputop_free_events_names(char **names); ================================================ FILE: server/gputop-gl.c ================================================ /* * GPU Top * * Copyright (C) 2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include /* NB: We use a portable stdatomic.h, so we don't depend on a recent compiler... */ #include "stdatomic.h" #include #include "gputop-gl.h" #include "gputop-mainloop.h" #include "gputop-util.h" #include "gputop-sysutil.h" #include "gputop-log.h" /* XXX: As a GL interposer we have to be extra paranoid about * generating GL errors that might trample on the error state that the * application sees. * * For now we just try our best to never generate internal errors but * if we find we can't always guarantee that then we should be able to * intercept the KHR_debug extension and glGetError() to effectively * hide any internal errors. */ #define GE(X) \ do { \ GLenum __err; \ X; \ while ((__err = pfn_glGetError()) != GL_NO_ERROR) \ dbg("GL error (%d):\n", __err); \ } while(0) #define GE_RET(ret, X) \ do { \ GLenum __err; \ ret = X; \ while ((__err = pfn_glGetError()) != GL_NO_ERROR) \ dbg("GL error (%d):\n", __err); \ } while(0) static pthread_once_t init_once = PTHREAD_ONCE_INIT; static pthread_key_t winsys_context_key; static void *(*real_glXGetProcAddress)(const GLubyte *procName); static Bool (*real_glXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx); static Bool (*real_glXMakeContextCurrent)(Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx); static GLXFBConfig *(*real_glXChooseFBConfig)(Display *dpy, int screen, const int *attrib_list, int *nelements); static int (*real_glXGetConfig)(Display *dpy, XVisualInfo *vis, int attrib, int *value); static GLXContext (*real_glXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct); static GLXContext (*real_glXCreateNewContext)(Display *dpy, GLXFBConfig config, int render_type, GLXContext share_list, Bool direct); static GLXContext (*real_glXCreateContextAttribsARB)(Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list); static void (*real_glXDestroyContext)(Display *dpy, GLXContext glx_ctx); static void (*real_glXSwapBuffers)(Display *dpy, GLXDrawable drawable); static pthread_once_t initialise_gl_once = PTHREAD_ONCE_INIT; static const GLubyte *(*pfn_glGetStringi)(GLenum name, GLuint index); static const GLubyte *(*pfn_glGetString)(GLenum name); static void (*pfn_glGetIntegerv)(GLenum pname, GLint *params); static GLenum (*pfn_glGetError)(void); static void (*pfn_glEnable)(GLenum cap); static bool (*pfn_glIsEnabled)(GLenum cap); static void (*pfn_glDisable)(GLenum cap); static void (*pfn_glScissor)(GLint x, GLint y, GLsizei width, GLsizei height); static void (*pfn_glDebugMessageControl)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); static void (*pfn_glDebugMessageCallback)(GLDEBUGPROC callback, const void *userParam); static void (*pfn_glGetPerfQueryInfoINTEL)(GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *maxInstances, GLuint *noActiveInstances, GLuint *capsMask); static void (*pfn_glGetPerfCounterInfoINTEL)(GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); static void (*pfn_glGetFirstPerfQueryIdINTEL)(GLuint *queryId); static void (*pfn_glGetNextPerfQueryIdINTEL)(GLuint queryId, GLuint *nextQueryId); static void (*pfn_glGetPerfQueryIdByNameINTEL)(GLchar *queryName, GLuint *queryId); static void (*pfn_glCreatePerfQueryINTEL)(GLuint queryId, GLuint *queryHandle); static void (*pfn_glDeletePerfQueryINTEL)(GLuint queryHandle); static void (*pfn_glBeginPerfQueryINTEL)(GLuint queryHandle); static void (*pfn_glEndPerfQueryINTEL)(GLuint queryHandle); static void (*pfn_glGetPerfQueryDataINTEL)(GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten); void * gputop_glXGetProcAddress(const GLubyte *procName); static bool gputop_gl_has_khr_debug_ext; static bool gputop_gl_use_khr_debug; bool gputop_gl_has_intel_performance_query_ext; /* * gputop_gl_lock is the lock generally used by the server thread to * safely access GL state. * * It protects the top level arrays of contexts and surfaces and the * modification of all their internal state with a few exceptions: * * - gputop_gl_lock does not stop the GL thread from appending to * wsurface->finished_queries lists. Instead see * wsurface->finished_queries_lock * * - gputop_gl_lock does not stop the UI thread from appending to the * wctx->query_obj_cache list. Instead see * wctx->query_obj_cache_lock. * * These special cases cover the GL state that's expected to change * most frequently so that the server thread taking gputop_gl_lock * while redrawing won't typically block anything in the GL thread. */ pthread_rwlock_t gputop_gl_lock = PTHREAD_RWLOCK_INITIALIZER; struct array *gputop_gl_contexts; struct array *gputop_gl_surfaces; bool gputop_gl_force_debug_ctx_enabled = false; atomic_bool gputop_gl_scissor_test_enabled; atomic_bool gputop_gl_monitoring_enabled; atomic_int gputop_gl_n_queries; void * gputop_passthrough_gl_resolve(const char *name) { static void *libgl_handle = NULL; if (!libgl_handle) { const char *libgl_filename = getenv("GPUTOP_GL_LIBRARY"); if (!libgl_filename) libgl_filename = "/usr/lib/libGL.so.1"; libgl_handle = dlopen(libgl_filename, RTLD_LAZY | RTLD_GLOBAL); if (!libgl_handle) { fprintf(stderr, "gputop: Failed to open %s library: %s", libgl_filename, dlerror()); exit(EXIT_FAILURE); } } return dlsym(libgl_handle, name); } void * gputop_passthrough_glx_resolve(const char *name) { return gputop_passthrough_gl_resolve(name); } void * gputop_passthrough_egl_resolve(const char *name) { static void *libegl_handle = NULL; if (!libegl_handle) { const char *libegl_filename = getenv("GPUTOP_EGL_LIBRARY"); if (!libegl_filename) libegl_filename = "/usr/lib/libEGL.so.1"; libegl_handle = dlopen(libegl_filename, RTLD_LAZY | RTLD_GLOBAL); if (!libegl_handle) { fprintf(stderr, "gputop: Failed to open %s library: %s", libegl_filename, dlerror()); exit(EXIT_FAILURE); } } return dlsym(libegl_handle, name); } static void glx_winsys_init(void) { real_glXGetProcAddress = gputop_passthrough_gl_resolve("glXGetProcAddress"); real_glXMakeCurrent = gputop_passthrough_gl_resolve("glXMakeCurrent"); real_glXMakeContextCurrent = gputop_passthrough_gl_resolve("glXMakeContextCurrent"); real_glXChooseFBConfig = gputop_passthrough_gl_resolve("glXChooseFBConfig"); real_glXGetConfig = gputop_passthrough_gl_resolve("glXGetConfig"); real_glXCreateContext = gputop_passthrough_gl_resolve("glXCreateContext"); real_glXCreateNewContext = gputop_passthrough_gl_resolve("glXCreateNewContext"); real_glXCreateContextAttribsARB = real_glXGetProcAddress((GLubyte *)"glXCreateContextAttribsARB"); real_glXDestroyContext = gputop_passthrough_gl_resolve("glXDestroyContext"); real_glXSwapBuffers = gputop_passthrough_gl_resolve("glXSwapBuffers"); } static void gputop_gl_init(void) { glx_winsys_init(); pthread_key_create(&winsys_context_key, NULL); gputop_gl_contexts = array_new(sizeof(void *), 5); gputop_gl_surfaces = array_new(sizeof(void *), 5); if (gputop_get_bool_env("GPUTOP_GL_DEBUG_CONTEXT")) gputop_gl_force_debug_ctx_enabled = true; if (gputop_get_bool_env("GPUTOP_GL_SCISSOR_TEST")) atomic_store(&gputop_gl_scissor_test_enabled, true); else atomic_store(&gputop_gl_scissor_test_enabled, false); } static void gputop_abort(const char *error) __attribute__((noreturn)); static void gputop_abort(const char *error) { if (gputop_mainloop) { uv_idle_t idle; uv_idle_init(gputop_mainloop, &idle); idle.data = (void *)error; uv_idle_start(&idle, gputop_mainloop_quit_idle_cb); for (;;) ; } fprintf(stderr, "%s", error); fflush(stderr); exit(EXIT_FAILURE); } /* XXX: we implement this passthrough implementation of glXQueryExtension * because some frameworks (namely SDL) that directly dlopen() libGL.so.1 * expect to use dlsym() to find glXGetProcAddress and glXQueryExtension. We * have an LD_PRELOAD wrapper for dlopen() that forwards a handle to * libfakeGL.so instead of the real libGL.so so we need to make sure SDL can * resolve glXQueryExtension - part of the never ending Whack A Mole * interposing OpenGL. */ Bool gputop_glXQueryExtension(Display *dpy, int *errorBase, int *eventBase) { static Bool (*pfn_glXQueryExtension)(Display *dpy, int *errorBase, int *eventBase); if (!pfn_glXQueryExtension) pfn_glXQueryExtension = gputop_passthrough_gl_resolve("glXQueryExtension"); return pfn_glXQueryExtension(dpy, errorBase, eventBase); } void * gputop_glXGetProcAddressARB(const GLubyte *procName) { return gputop_glXGetProcAddress(procName); } /* While we are relying on LD_PRELOAD to intercept certain GLX/GL functions we * need to handle the possibility that some GL applications/frameworks will use * dlopen() at runtime to load libGL.so and trick them into opening our * libfakeGL.so instead. */ void *dlopen(const char *filename, int flag) { static void *(*real_dlopen)(const char *filename, int flag); if (filename && strncmp(filename, "libGL.so", 8) == 0) { /* * We're assuming that libfakeGL.so was forcibly loaded via LD_PRELOAD * so lookups based on a dlopen(NULL) handle should find libfakeGL.so * symbols. */ return dlopen(NULL, flag); } else { if (!real_dlopen) real_dlopen = dlsym(RTLD_NEXT, "dlopen"); return real_dlopen(filename, flag); } } static bool have_extension(const char *name) { const char *gl_extensions = (const char *)pfn_glGetString(GL_EXTENSIONS); int n_extensions = 0; int i; /* Note: we're not currently being careful to consider extension * names that are an abbreviation of another name... */ if (gl_extensions) return strstr(gl_extensions, name); if (pfn_glGetError() != GL_INVALID_ENUM || pfn_glGetStringi == NULL) gputop_abort("Spurious NULL from glGetString(GL_EXTENSIONS)"); /* If we got GL_INVALID_ENUM lets just assume we have a core * profile context so we need to use glGetStringi() */ pfn_glGetIntegerv(GL_NUM_EXTENSIONS, &n_extensions); if (!n_extensions) gputop_abort("glGetIntegerv(GL_NUM_EXTENSIONS) returned zero"); for (i = 0; i < n_extensions; i++) if (strcmp(name, (char *)pfn_glGetStringi(GL_EXTENSIONS, i)) == 0) return true; return false; } static void initialise_gl(void) { #define SYM(X) { #X, (void **)&pfn_##X } struct { const char *name; void **ptr; } symbols[] = { SYM(glGetString), SYM(glGetStringi), SYM(glGetIntegerv), SYM(glGetError), SYM(glEnable), SYM(glIsEnabled), SYM(glDisable), SYM(glScissor), /* KHR_debug */ SYM(glDebugMessageControl), SYM(glDebugMessageCallback), /* GL_INTEL_performance_query */ SYM(glGetPerfQueryInfoINTEL), SYM(glGetPerfCounterInfoINTEL), SYM(glGetFirstPerfQueryIdINTEL), SYM(glGetNextPerfQueryIdINTEL), SYM(glGetPerfQueryIdByNameINTEL), SYM(glCreatePerfQueryINTEL), SYM(glDeletePerfQueryINTEL), SYM(glBeginPerfQueryINTEL), SYM(glEndPerfQueryINTEL), SYM(glGetPerfQueryDataINTEL), }; #undef SYM int i; for (i = 0; i < sizeof(symbols) / sizeof(symbols[0]); i++) *(symbols[i].ptr) = real_glXGetProcAddress((GLubyte *)symbols[i].name); gputop_gl_has_intel_performance_query_ext = have_extension("GL_INTEL_performance_query"); gputop_gl_has_khr_debug_ext = have_extension("GL_KHR_debug"); } static struct intel_query_info * get_query_info(unsigned id) { struct intel_query_info *query_info = xmalloc0(sizeof(*query_info)); int i; query_info->id = id; pfn_glGetPerfQueryInfoINTEL( id, sizeof(query_info->name), query_info->name, &query_info->max_counter_data_len, &query_info->n_counters, &query_info->max_queries, &query_info->n_active_queries, &query_info->caps_mask); for (i = 0; i < query_info->n_counters && i < MAX_QUERY_COUNTERS; i++) { struct intel_counter *counter = &query_info->counters[i]; /* XXX: INTEL_performance_query reserves id 0 with sequential * counter ids, base 1 */ counter->id = i + 1; pfn_glGetPerfCounterInfoINTEL( id, counter->id, sizeof(counter->name), counter->name, sizeof(counter->description), counter->description, &counter->data_offset, &counter->data_size, &counter->type, &counter->data_type, &counter->max_raw_value); } return query_info; } static struct gl_perf_query * query_obj_cache_pop(struct winsys_context *wctx) { struct gl_perf_query *first; pthread_rwlock_wrlock(&wctx->query_obj_cache_lock); first = list_first_entry(&wctx->query_obj_cache, struct gl_perf_query, link); if (first) list_del(&first->link); pthread_rwlock_unlock(&wctx->query_obj_cache_lock); return first; } static void query_obj_destroy(struct gl_perf_query *obj) { GE(pfn_glDeletePerfQueryINTEL(obj->handle)); atomic_fetch_sub(&gputop_gl_n_queries, 1); free(obj); } static void query_obj_cache_destroy(struct winsys_context *wctx) { list_for_each_entry_safe(struct gl_perf_query, obj, &wctx->query_obj_cache, link) { list_del(&obj->link); query_obj_destroy(obj); } } static void gputop_khr_debug_callback(GLenum source, GLenum type, GLuint id, GLenum gl_severity, GLsizei length, const GLchar *message, void *userParam) { int level = GPUTOP_LOG_LEVEL_NOTIFICATION; switch (gl_severity) { case GL_DEBUG_SEVERITY_HIGH: level = GPUTOP_LOG_LEVEL_HIGH; break; case GL_DEBUG_SEVERITY_MEDIUM: level = GPUTOP_LOG_LEVEL_MEDIUM; break; case GL_DEBUG_SEVERITY_LOW: level = GPUTOP_LOG_LEVEL_LOW; break; case GL_DEBUG_SEVERITY_NOTIFICATION: level = GPUTOP_LOG_LEVEL_NOTIFICATION; break; } gputop_log(level, message, length); } static void winsys_context_gl_initialise(struct winsys_context *wctx) { unsigned query_id = 0; pthread_once(&initialise_gl_once, initialise_gl); pfn_glGetFirstPerfQueryIdINTEL(&query_id); /* NB: we need to be paranoid about leaking GL errors to the application */ while (pfn_glGetError() != GL_NO_ERROR) ; while (query_id) { struct intel_query_info *query_info = get_query_info(query_id); list_addtail(&query_info->link, &wctx->queries); pfn_glGetNextPerfQueryIdINTEL(query_id, &query_id); while (pfn_glGetError() != GL_NO_ERROR) ; } gputop_gl_use_khr_debug = gputop_gl_has_khr_debug_ext && gputop_get_bool_env("GPUTOP_GL_DEBUG_CONTEXT"); if (gputop_gl_use_khr_debug) { pfn_glDebugMessageControl(GL_DONT_CARE, /* source */ GL_DONT_CARE, /* type */ GL_DONT_CARE, /* severity */ 0, NULL, false); pfn_glDebugMessageControl(GL_DONT_CARE, /* source */ GL_DEBUG_TYPE_PERFORMANCE, GL_DONT_CARE, /* severity */ 0, NULL, true); pfn_glDisable(GL_DEBUG_OUTPUT); wctx->khr_debug_enabled = false; pfn_glDebugMessageCallback((GLDEBUGPROC)gputop_khr_debug_callback, wctx); } } static struct winsys_context * winsys_context_create(GLXContext glx_ctx) { struct winsys_context *wctx = xmalloc0(sizeof(struct winsys_context)); wctx->glx_ctx = glx_ctx; wctx->gl_initialised = false; wctx->ref++; list_inithead(&wctx->queries); list_inithead(&wctx->query_obj_cache); pthread_rwlock_init(&wctx->query_obj_cache_lock, NULL); pthread_rwlock_wrlock(&gputop_gl_lock); array_append(gputop_gl_contexts, &wctx); pthread_rwlock_unlock(&gputop_gl_lock); return wctx; } GLXContext gputop_glXCreateContextAttribsARB(Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list) { GLXContext glx_ctx; bool is_debug_context = false; struct winsys_context *wctx; int i; pthread_once(&init_once, gputop_gl_init); if (gputop_gl_force_debug_ctx_enabled) { int n_attribs; int flags_index; int *attribs_copy; for (n_attribs = 0; attrib_list[n_attribs] != None; n_attribs += 2) ; attribs_copy = alloca(sizeof(int) * n_attribs + 3); memcpy(attribs_copy, attrib_list, sizeof(int) * (n_attribs + 1)); for (flags_index = 0; (flags_index < n_attribs && attrib_list[flags_index] != GLX_CONTEXT_FLAGS_ARB); flags_index += 2) ; if (flags_index == n_attribs) { attribs_copy[n_attribs++] = GLX_CONTEXT_FLAGS_ARB; attribs_copy[n_attribs++] = 0; attribs_copy[n_attribs] = None; } attribs_copy[flags_index + 1] = GLX_CONTEXT_DEBUG_BIT_ARB; attrib_list = attribs_copy; is_debug_context = true; } for (i = 0; attrib_list[i] != None; i += 2) { if (attrib_list[i] == GLX_CONTEXT_FLAGS_ARB && attrib_list[i+1] & GLX_CONTEXT_DEBUG_BIT_ARB) { is_debug_context = true; } } glx_ctx = real_glXCreateContextAttribsARB(dpy, config, share_context, direct, attrib_list); if (!glx_ctx) return glx_ctx; wctx = winsys_context_create(glx_ctx); wctx->is_debug_context = is_debug_context; return glx_ctx; } GLXContext gputop_glXCreateNewContext(Display *dpy, GLXFBConfig config, int render_type, GLXContext share_list, Bool direct) { int attrib_list[] = { GLX_RENDER_TYPE, render_type, None }; return gputop_glXCreateContextAttribsARB(dpy, config, share_list, direct, attrib_list); } static GLXContext try_create_new_context(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct) { int attrib_list[3] = { GLX_FBCONFIG_ID, None, None }; int n_configs; int fb_config_id; GLXFBConfig *configs; GLXContext glx_ctx = NULL; real_glXGetConfig(dpy, vis, GLX_FBCONFIG_ID, &fb_config_id); attrib_list[1] = fb_config_id; configs = real_glXChooseFBConfig(dpy, vis->screen, attrib_list, &n_configs); if (n_configs == 1) { glx_ctx = gputop_glXCreateNewContext(dpy, configs[0], GLX_RGBA, shareList, direct); } XFree(configs); return glx_ctx; } GLXContext gputop_glXCreateContext(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct) { GLXContext glx_ctx; struct winsys_context *wctx; pthread_once(&init_once, gputop_gl_init); /* We'd rather be able to use glXCreateContextAttribsARB() so that * we can optionally create a debug context, but sometimes it's * not possible to map a visual to an fbconfig. */ glx_ctx = try_create_new_context(dpy, vis, shareList, direct); if (glx_ctx) return glx_ctx; glx_ctx = real_glXCreateContext(dpy, vis, shareList, direct); if (!glx_ctx) return NULL; wctx = winsys_context_create(glx_ctx); wctx->try_create_new_context_failed = true; return glx_ctx; } static struct winsys_context * winsys_context_lookup(GLXContext glx_ctx, int *idx) { struct winsys_context **contexts = gputop_gl_contexts->data; int i; for (i = 0; i < gputop_gl_contexts->len; i++) { struct winsys_context *wctx = contexts[i]; if (wctx->glx_ctx == glx_ctx) { *idx = i; return wctx; } } return NULL; } static void winsys_context_destroy(struct winsys_context *wctx) { int idx; pthread_rwlock_wrlock(&gputop_gl_lock); winsys_context_lookup(wctx->glx_ctx, &idx); array_remove_fast(gputop_gl_contexts, idx); pthread_rwlock_unlock(&gputop_gl_lock); list_for_each_entry_safe(struct intel_query_info, q, &wctx->queries, link) { list_del(&q->link); free(q); } if (wctx->draw_wsurface) wctx->draw_wsurface->wctx = NULL; if (wctx->read_wsurface) wctx->read_wsurface->wctx = NULL; free(wctx); } void gputop_glXDestroyContext(Display *dpy, GLXContext glx_ctx) { struct winsys_context *wctx; int context_idx; pthread_once(&init_once, gputop_gl_init); wctx = winsys_context_lookup(glx_ctx, &context_idx); if (wctx) { if (--wctx->ref == 0) winsys_context_destroy(wctx); } else dbg("Spurious glXDestroyContext for unknown glx context"); } /* XXX: We don't currently have a way of knowing when a window has * been destroyed for us to free winsys_surface state, so we just * *hope* applications don't create too many! * * If we didn't start *and* finish frame queries in glXSwapBuffers but * instead hooked into GL apis that can submit drawing commands for * marking the start of frames, then we'd potentially be able to * reference count winsys_surface state. This would likely be very * fragile though since GL can always be extended with new drawing * apis and we'd have to keep up with hooking into all of them. * * In an ideal world we'd have a GL extension that would let us * register a callback so the GL implementation could notify us when * a frame start (at a point where there is a context current) which * would be future proof. */ static struct winsys_surface * winsys_surface_create(struct winsys_context *wctx, GLXWindow glx_window) { struct winsys_surface *wsurface = xmalloc(sizeof(struct winsys_surface)); memset(wsurface, 0, sizeof(struct winsys_surface)); /* XXX: gputop only supports drawables accessed from a single * context (see comment in glXSwapBuffers for further details * why) */ wsurface->wctx = wctx; wsurface->glx_window = glx_window; list_inithead(&wsurface->pending_queries); list_inithead(&wsurface->finished_queries); pthread_rwlock_init(&wsurface->finished_queries_lock, NULL); pthread_rwlock_wrlock(&gputop_gl_lock); array_append(gputop_gl_surfaces, &wsurface); pthread_rwlock_unlock(&gputop_gl_lock); return wsurface; } static struct winsys_surface * get_wsurface(struct winsys_context *wctx, GLXWindow glx_window) { struct winsys_surface **surfaces = gputop_gl_surfaces->data; int i; for (i = 0; i < gputop_gl_surfaces->len; i++) { struct winsys_surface *wsurface = surfaces[i]; if (wsurface->glx_window == glx_window) { if (wsurface->wctx != wctx) gputop_abort("gputop doesn't support applications accessing one drawable from multiple contexts"); return wsurface; } } /* XXX: we don't try and hook into glXCreateWindow as a place * to initialise winsys_surface state since GLX allows * applications to pass a vanilla Window xid as a glx drawable * without calling glXCreateWindow. * * XXX: we're currently assuming the passed xid is a window, * although it might actually be a GLXPixmap. */ return winsys_surface_create(wctx, glx_window); } static bool make_context_current(Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext glx_ctx) { struct winsys_context *prev_wctx; struct winsys_context *wctx; int wctx_idx; Bool ret; pthread_once(&init_once, gputop_gl_init); prev_wctx = pthread_getspecific(winsys_context_key); ret = real_glXMakeContextCurrent(dpy, draw, read, glx_ctx); if (!ret) return ret; wctx = winsys_context_lookup(glx_ctx, &wctx_idx); if (glx_ctx && !wctx) { gputop_abort("Spurious glXMakeCurrent with unknown glx context\n" "\n" "GPU Top may be missing support for some new GLX API for creating contexts?\n"); } pthread_setspecific(winsys_context_key, wctx); /* NB: we can't simply bail here if prev_wctx == wctx since * the drawables may have changed */ /* NB: GLX ref counts contexts so they are only destroyed when * they are no longer current in any thread. */ if (wctx) wctx->ref++; if (prev_wctx && --prev_wctx->ref == 0) { winsys_context_destroy(prev_wctx); prev_wctx = NULL; } if (!wctx) return ret; if (!wctx->gl_initialised) winsys_context_gl_initialise(wctx); /* XXX: We have to make some assumptions about how applications * use GLX to be able to start and stop performance queries on * frame boundaries... * * In particular we are hooking into glXSwapBuffers as a way to * delimit frames but glXSwapBuffers acts on a drawable without * requiring a GL context to be current in the calling thread. * * Since we need to use the GL_INTEL_performance_query extension * to start and stop queries we do require there to be a context * current though. * * There will be software in the wild that will defer swap buffers * to a separate thread as a way to avoid blocking a rendering * thread but gputop won't be able to handle this situation. * * gtop explicitly imposes the constraint that a drawable can only * be made current in one context at a time and the constraint * that that context must be current during glXSwapBuffers. */ wctx->draw_wsurface = get_wsurface(wctx, draw); wctx->draw_wsurface->wctx = wctx; if (read != draw) { wctx->read_wsurface = get_wsurface(wctx, read); wctx->read_wsurface->wctx = wctx; } return ret; } Bool gputop_glXMakeCurrent(Display *dpy, GLXDrawable drawable, GLXContext glx_ctx) { return make_context_current(dpy, drawable, drawable, glx_ctx); } Bool gputop_glXMakeContextCurrent(Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx) { return make_context_current(dpy, draw, read, ctx); } static void winsys_surface_start_frame(struct winsys_surface *wsurface) { struct winsys_context *wctx = wsurface->wctx; struct gl_perf_query *obj; if (!wctx->current_query) return; obj = query_obj_cache_pop(wctx); if (!obj) { struct intel_query_info *info = wctx->current_query; obj = xmalloc0(sizeof(struct gl_perf_query) + info->max_counter_data_len); GE(pfn_glCreatePerfQueryINTEL(info->id, &obj->handle)); atomic_fetch_add(&gputop_gl_n_queries, 1); } /* XXX: We're assuming that a BeginPerfQuery doesn't implicitly * flush anything to the hardware since we don't want to start * measuring anything while there's no real work going on. * * It would be good to have a unit test that makes sure we * maintain this behaviour in Mesa even though it doesn't seem to * be explicitly guaranteed by the spec. */ GE(pfn_glBeginPerfQueryINTEL(obj->handle)); /* not pending until glEndPerfQueryINTEL is called... */ wsurface->open_query_obj = obj; } static void winsys_surface_end_frame(struct winsys_surface *wsurface) { if (wsurface->open_query_obj) { pfn_glEndPerfQueryINTEL(wsurface->open_query_obj->handle); list_addtail(&wsurface->open_query_obj->link, &wsurface->pending_queries); wsurface->open_query_obj = NULL; } } static void winsys_surface_check_for_finished_queries(struct winsys_surface *wsurface) { struct winsys_context *wctx = wsurface->wctx; struct list_head finished; list_inithead(&finished); list_for_each_entry_safe(struct gl_perf_query, obj, &wsurface->pending_queries, link) { unsigned data_len = 0; GE(pfn_glGetPerfQueryDataINTEL( obj->handle, GL_PERFQUERY_DONOT_FLUSH_INTEL, wctx->current_query->max_counter_data_len, obj->data, &data_len)); if (data_len) { list_del(&obj->link); list_addtail(&obj->link, &finished); } else break; } /* FIXME: we should throttle here if we're somehow producing too * much data for the UI to process? */ pthread_rwlock_wrlock(&wsurface->finished_queries_lock); list_addtail(&finished, &wsurface->finished_queries); pthread_rwlock_unlock(&wsurface->finished_queries_lock); } static void winsys_surface_delete_surface_queries(struct winsys_surface *wsurface) { if (wsurface->open_query_obj) { query_obj_destroy(wsurface->open_query_obj); wsurface->open_query_obj = NULL; } list_for_each_entry_safe(struct gl_perf_query, obj, &wsurface->pending_queries, link) { list_del(&obj->link); query_obj_destroy(obj); } list_for_each_entry_safe(struct gl_perf_query, obj, &wsurface->finished_queries, link) { list_del(&obj->link); query_obj_destroy(obj); } } /* XXX: The GLX api allows multiple threads to render to the same * drawable and glXSwapBuffers doesn't refer to the current GL * context it is an operation on a drawable visible to all * contexts. * * gputop currently assumes this is all madness and only allows a * drawable to be current in a single thread at a time and * therefore only associated with a single context otherwise we * couldn't drive per-frame queries from here since we'd have no * way of knowing which context to create + begin the queries * with. * * If we do end up needing to profile something binding * drawables into multiple threads at the same time then we will * need to hook into all GL entry points that can submit commands * to the gpu so that the first command after a swap-buffers * would implicitly start a new frame. We would still end the * queries here though (for all contexts). */ void gputop_glXSwapBuffers(Display *dpy, GLXDrawable drawable) { struct winsys_context *wctx; struct winsys_surface *wsurface; bool monitoring_enabled; bool scissor_test; pthread_once(&init_once, gputop_gl_init); wctx = pthread_getspecific(winsys_context_key); if (!wctx) gputop_abort("gputop can't support applications calling glXSwapBuffers without a current context"); wsurface = get_wsurface(wctx, drawable); if (wsurface->wctx != wctx) gputop_abort("gputop can't support applications calling glXSwapBuffers with a drawable not bound to calling thread's current context"); if (gputop_gl_use_khr_debug != wctx->khr_debug_enabled) { if (wctx->khr_debug_enabled) pfn_glEnable(GL_DEBUG_OUTPUT); else pfn_glDisable(GL_DEBUG_OUTPUT); } monitoring_enabled = atomic_load(&gputop_gl_monitoring_enabled); if (!monitoring_enabled) { struct winsys_surface **surfaces; int i; pthread_rwlock_wrlock(&gputop_gl_lock); surfaces = gputop_gl_surfaces->data; for (i = 0; i < gputop_gl_surfaces->len; i++) { winsys_surface_delete_surface_queries(surfaces[i]); } pthread_rwlock_wrlock(&wctx->query_obj_cache_lock); query_obj_cache_destroy(wctx); pthread_rwlock_unlock(&wctx->query_obj_cache_lock); pthread_rwlock_unlock(&gputop_gl_lock); } if (monitoring_enabled) winsys_surface_end_frame(wsurface); real_glXSwapBuffers(dpy, drawable); scissor_test = atomic_load(&gputop_gl_scissor_test_enabled); if (scissor_test) { pfn_glScissor(0, 0, 1, 1); if (!pfn_glIsEnabled(GL_SCISSOR_TEST)) pfn_glEnable(GL_SCISSOR_TEST); } else { pfn_glScissor(wctx->scissor_x, wctx->scissor_y, wctx->scissor_width, wctx->scissor_height); if (wctx->scissor_enabled) pfn_glEnable(GL_SCISSOR_TEST); else pfn_glDisable(GL_SCISSOR_TEST); } if (monitoring_enabled) { winsys_surface_check_for_finished_queries(wsurface); winsys_surface_start_frame(wsurface); } } void gputop_glEnable(GLenum cap) { struct winsys_context *wctx = pthread_getspecific(winsys_context_key); if (gputop_gl_use_khr_debug && cap == GL_DEBUG_OUTPUT) { dbg("Ignoring application's conflicting use of KHR_debug extension"); return; } if (cap == GL_SCISSOR_TEST) { wctx->scissor_enabled = true; } pfn_glEnable(cap); } void gputop_glDisable(GLenum cap) { struct winsys_context *wctx; bool scissor_test; wctx = pthread_getspecific(winsys_context_key); scissor_test = atomic_load(&gputop_gl_scissor_test_enabled); if (gputop_gl_use_khr_debug && cap == GL_DEBUG_OUTPUT) { dbg("Ignoring application's conflicting use of KHR_debug extension"); return; } if (cap == GL_SCISSOR_TEST) { wctx->scissor_enabled = false; } if (!scissor_test || (cap != GL_SCISSOR_TEST)) { pfn_glDisable(cap); } } void gputop_glScissor(GLint x, GLint y, GLsizei width, GLsizei height) { struct winsys_context *wctx = pthread_getspecific(winsys_context_key); wctx->scissor_x = x; wctx->scissor_y = y; wctx->scissor_width = width; wctx->scissor_height = height; if (!atomic_load(&gputop_gl_scissor_test_enabled)) pfn_glScissor(x, y, width, height); } void gputop_glDebugMessageControl(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled) { dbg("Ignoring application's conflicting use of KHR_debug extension"); } void gputop_glDebugMessageCallback(GLDEBUGPROC callback, const void *userParam) { dbg("Ignoring application's conflicting use of KHR_debug extension"); } void * gputop_glXGetProcAddress(const GLubyte *procName) { int i; #define SYM(X) { #X, (void **)&gputop_ ## X } struct { const char *name; void **ptr; } static symbols[] = { SYM(glXCreateContextAttribsARB), SYM(glXCreateNewContext), SYM(glXCreateContext), SYM(glXDestroyContext), SYM(glXMakeCurrent), SYM(glXMakeContextCurrent), SYM(glXSwapBuffers), SYM(glEnable), SYM(glDisable), SYM(glScissor), SYM(glDebugMessageControl), SYM(glDebugMessageCallback) }; #undef SYM pthread_once(&init_once, gputop_gl_init); if (strcmp((char *)procName, "glXCreateContextWithConfigSGIX") == 0) return NULL; for (i = 0; i < (sizeof(symbols) / sizeof(symbols[0])); i++) { if (strcmp((char *)procName, symbols[i].name) == 0) return (symbols[i].ptr); } return real_glXGetProcAddress(procName); } ================================================ FILE: server/gputop-gl.h ================================================ /* * GPU Top * * Copyright (C) 2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef _GPUTOP_GL_H_ #define _GPUTOP_GL_H_ #include #include /* NB: We use a portable stdatomic.h, so we don't depend on a recent compiler... */ #include "stdatomic.h" #include "util/list.h" struct intel_counter { uint64_t max_raw_value; unsigned id; unsigned type; unsigned data_offset; unsigned data_size; unsigned data_type; char name[64]; char description[256]; }; #define MAX_QUERY_COUNTERS 1000 struct intel_query_info { struct list_head link; unsigned id; unsigned n_counters; unsigned max_queries; unsigned n_active_queries; unsigned max_counter_data_len; unsigned caps_mask; struct intel_counter counters[MAX_QUERY_COUNTERS]; char name[128]; }; struct gl_perf_query { struct list_head link; struct intel_query_info *info; unsigned handle; uint8_t data[]; /* len == query_info->max_counter_data_len */ }; struct winsys_context { int ref; GLXContext glx_ctx; /* TODO: Add EGL support */ struct winsys_surface *read_wsurface; struct winsys_surface *draw_wsurface; bool gl_initialised; struct list_head queries; struct intel_query_info *current_query; pthread_rwlock_t query_obj_cache_lock; struct list_head query_obj_cache; bool try_create_new_context_failed; bool is_debug_context; bool khr_debug_enabled; GLint scissor_x; GLint scissor_y; GLsizei scissor_width; GLsizei scissor_height; bool scissor_enabled; }; struct winsys_surface { struct winsys_context *wctx; /* Ignore pixmaps for now */ GLXWindow glx_window; /* TODO: Add EGL support */ /* not pending until glEndPerfQueryINTEL is called... */ struct gl_perf_query *open_query_obj; struct list_head pending_queries; /* Finished queries, waiting to be picked up by the server thread */ pthread_rwlock_t finished_queries_lock; struct list_head finished_queries; }; extern bool gputop_gl_has_intel_performance_query_ext; extern pthread_rwlock_t gputop_gl_lock; extern struct array *gputop_gl_contexts; extern struct array *gputop_gl_surfaces; extern bool gputop_gl_force_debug_ctx_enabled; extern atomic_bool gputop_gl_monitoring_enabled; extern atomic_bool gputop_gl_khr_debug_enabled; extern atomic_bool gputop_gl_scissor_test_enabled; /* The number of query objects to delete if GL monitoring is disabled... * * We aim to delete all query objects when switching between GL * performance queries as a way to tell OpenGL will relinquish any * exclusive state associated with the previous query that might block * us from opening a new query or starting to collect system wide * metrics. * * The deletion of query objects is handled with swap-buffers which * which depends on being called by the application. The server * thread can check this atomic counter as a way to report * to the user that we're still busy waiting for GL. */ extern atomic_int gputop_gl_n_queries; #endif /* _GPUTOP_GL_H_ */ ================================================ FILE: server/gputop-ioctl.c ================================================ #include #include #include "gputop-perf.h" int ioctl(int fd, unsigned long request, void *data) { static int (*real_ioctl) (int fd, unsigned long request, void *data); int ret; if (!real_ioctl) real_ioctl = dlsym(RTLD_NEXT, "ioctl"); ret = real_ioctl(fd, request, data); if (!ret) { /* Contexts are specific to the drm_file instance used in rendering. * The ctx_id created by the kernel is _not_ globally * unique, but rather unique for that drm_file instance. * For example from the global context_list, there will be multiple * default contexts (0), but actually only one of these per file instance. * Therefore to properly enable OA metrics on a per-context basis, we * need the file descriptor and the ctx_id. */ if (request == DRM_IOCTL_I915_GEM_CONTEXT_CREATE) { struct drm_i915_gem_context_create *ctx_create = data; gputop_add_ctx_handle(fd, ctx_create->ctx_id); } else if (request == DRM_IOCTL_I915_GEM_CONTEXT_DESTROY) { struct drm_i915_gem_context_destroy *ctx_destroy = data; gputop_remove_ctx_handle(ctx_destroy->ctx_id); } } return ret; } ================================================ FILE: server/gputop-log.c ================================================ /* * GPU Top * * Copyright (C) 2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include "gputop-util.h" #include "gputop-log.h" pthread_once_t gputop_log_init_once = PTHREAD_ONCE_INIT; pthread_rwlock_t gputop_log_lock = PTHREAD_RWLOCK_INITIALIZER; int gputop_log_len; struct list_head gputop_log_entries; void gputop_log_init(void) { list_inithead(&gputop_log_entries); } void gputop_log(int level, const char *message, int len) { struct gputop_log_entry *entry; pthread_once(&gputop_log_init_once, gputop_log_init); /* XXX: HACK */ printf("%s", message); if (len < 0) len = strlen(message); pthread_rwlock_wrlock(&gputop_log_lock); if (gputop_log_len > 10000) { entry = list_last_entry(&gputop_log_entries, struct gputop_log_entry, link); list_del(&entry->link); free(entry->msg); gputop_log_len--; } else entry = xmalloc(sizeof(*entry)); entry->level = level; entry->msg = strndup(message, len); list_addtail(&entry->link, &gputop_log_entries); gputop_log_len++; pthread_rwlock_unlock(&gputop_log_lock); } Gputop__Log * gputop_get_pb_log(void) { Gputop__Log *log = NULL; int i = 0; pthread_once(&gputop_log_init_once, gputop_log_init); if (!gputop_log_len) { return NULL; } pthread_rwlock_rdlock(&gputop_log_lock); log = xmalloc(sizeof(Gputop__Log)); gputop__log__init(log); log->n_entries = gputop_log_len; log->entries = xmalloc(gputop_log_len * sizeof(void *)); list_for_each_entry_safe(struct gputop_log_entry, entry, &gputop_log_entries, link) { Gputop__LogEntry *pb_entry = xmalloc(sizeof(Gputop__LogEntry)); gputop__log_entry__init(pb_entry); pb_entry->log_level = entry->level; pb_entry->log_message = entry->msg; /* steal the string */ log->entries[i] = pb_entry; i++; list_del(&entry->link); } gputop_log_len = 0; pthread_rwlock_unlock(&gputop_log_lock); return log; } void gputop_pb_log_free(Gputop__Log *log) { int i; if (log->n_entries) { for (i = 0; i < log->n_entries; i++) { Gputop__LogEntry *entry = log->entries[i]; free(entry->log_message); free(entry); } free(log->entries); } free(log); } ================================================ FILE: server/gputop-main.c ================================================ /* * GPU Top * * Copyright (C) 2013,2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "util/macros.h" /* We resolve the location of various libraries and files at runtime adding them * here so we can list them for user feedback... */ #define MAX_RESOURCES 10 static char *resource_locations[MAX_RESOURCES + 1]; static int n_resources = 0; static void list_resource(const char *resource, const char *location) { assert(n_resources < MAX_RESOURCES); asprintf(resource_locations + n_resources++, "%-15s at %s", resource, location); } static void usage(void) { printf("Usage: gputop [options] [program args...]\n" "\n" " --disable-ioctl-intercept Disable per-context monitoring by intercepting\n" " DRM_CONTEXT ioctl's\n" " without executing the program\n\n" " --disable-oaconfig Disable loading of OA configs\n\n" " --dry-run Print the environment variables\n" " without executing the program\n\n" " --fake Run gputop using fake metrics\n\n"); #ifdef SUPPORT_GL printf(" --libgl= Explicitly specify the real libGL\n" " library to intercept\n\n" " --libegl= Explicitly specify the real libEGL\n" " library to intercept\n\n" " --debug-gl-context Create a debug context and report\n" " KHR_debug perf issues\n\n" " --enable-gl-scissor-test Enable 1x1 scissor test\n" " glScissor(0, 0, 1, 1);\n"); #endif printf(" -h, --help Display this help\n\n" "\n" " Note: gputop is only a wrapper for setting environment variables\n" " including LD_LIBRARY_PATH to interpose OpenGL. For only viewing\n" " system-wide metrics (when no program is specified) gputop-system\n" " is run as a dummy 'GL' application.\n" "\n" " Environment:\n" "\n" " GPUTOP_DISABLE_OACONFIG=1 Prevents gputop to load OA configs\n" " GPUTOP_FAKE_MODE=1 Configure gputop to use fake mode\n" " GPUTOP_MODE=remote Currently only one mode\n" " GPUTOP_PORT=port Port gputop should listen to\n" "\n" " GPUTOP_TOPOLOGY_OVERRIDE=slice_mask,subslice_mask,n_eus_total\n" " Overrides slice mask, subslice mask and\n" " total number of EUs. This useful for testing\n" " on systems where part of the GT has been\n" " programmatically disabled.\n" "\n" #ifdef SUPPORT_GL " LD_PRELOAD=/lib/wrappers/libfakeGL.so:/lib/libgputop.so\n" " The gputop libGL.so and syscall\n" " interposer\n\n" " GPUTOP_GL_LIBRARY= Path to real libGL.so to chain\n" " up to from interposer\n\n" " GPUTOP_GL_DEBUG_CONTEXT=1 Force GL contexts to be debug\n" " contexts and report KHR_debug\n" " perf issues\n" #else " LD_PRELOAD=/lib/libgputop.so\n" " The gputop syscall interposer\n\n" #endif "\n" "" ); exit(1); } #ifdef SUPPORT_GL static bool resolve_lib_path_for_env(const char *lib, const char *sym_name, const char *env) { void *lib_handle; void *sym; Dl_info sym_info; lib_handle = dlopen(lib, RTLD_LAZY); if (!lib_handle) { fprintf(stderr, "gputop: Failed to dlopen \"%s\" while trying to resolve a default library path: %s\n", lib, dlerror()); return false; } sym = dlsym(lib_handle, sym_name); if (!sym) { fprintf(stderr, "gputop: Failed to lookup \"%s\" symbol while trying to resolve a default %s path: %s\n", sym_name, lib, dlerror()); exit(1); } if (dladdr(sym, &sym_info) == 0) { fprintf(stderr, "gputop: Failed to map %s symbol to a filename while trying to resolve a default %s path: %s\n", sym_name, lib, dlerror()); exit(1); } setenv(env, sym_info.dli_fname, true); if (dlclose(lib_handle) != 0) { fprintf(stderr, "gputop: Failed to close %s handle after resolving default library path: %s\n", lib, dlerror()); exit(1); } return true; } #endif static const char * get_bin_dir(void) { static const char *bin_dir = NULL; pid_t pid = getpid(); char *exe_link = NULL; char exe_path[1024]; if (bin_dir) return bin_dir; if (asprintf(&exe_link, "/proc/%d/exe", (int)pid) < 0) { perror(NULL); exit(1); } if (readlink(exe_link, exe_path, sizeof(exe_path)) < 0) { perror("Failed to resolve path of executable"); exit(1); } free(exe_link); exe_link = NULL; bin_dir = strdup(dirname(exe_path)); return bin_dir; } /* To help with running gputop from a build directory we search in a number of * different locations for different helper libraries to try and avoid muddling * a mixture of installed and build directory binaries. * * This also makes gputop binaries relocatable. */ static const char * const * get_lib_dirs(void) { static char *lib_dirs[7] = { 0 }; const char *bin_dir = get_bin_dir(); const char *prefix; char dir[1024]; int i = 0; if (lib_dirs[i] != NULL) return (const char * const *)lib_dirs; if (asprintf(&lib_dirs[i++], "%s", bin_dir) < 0) { perror("Failed to resolve libdir"); exit(1); } if (asprintf(&lib_dirs[i++], "%s/.libs", bin_dir) < 0) { perror("Failed to resolve libdir"); exit(1); } strncpy(dir, bin_dir, sizeof(dir)); prefix = dirname(dir); if (asprintf(&lib_dirs[i++], "%s/lib", prefix) < 0) { perror("Failed to resolve libdir"); exit(1); } if (asprintf(&lib_dirs[i++], "%s/lib/x86_64-linux-gnu", prefix) < 0) { perror("Failed to resolve libdir"); exit(1); } if (asprintf(&lib_dirs[i++], "%s/lib64", prefix) < 0) { perror("Failed to resolve libdir"); exit(1); } if (asprintf(&lib_dirs[i++], "%s/lib/wrappers", prefix) < 0) { perror("Failed to resolve libdir"); exit(1); } if (asprintf(&lib_dirs[i++], "%s/lib64/wrappers", prefix) < 0) { perror("Failed to resolve libdir"); exit(1); } assert(i <= ARRAY_SIZE(lib_dirs)); return (const char * const *)lib_dirs; } static char * resolve_gputop_lib(const char *lib) { const char * const *lib_dirs = get_lib_dirs(); for (int i = 0; lib_dirs[i]; i++) { char *path = NULL; struct stat sb; if (asprintf(&path, "%s/%s", lib_dirs[i], lib) < 0) { perror("Failed to format path to libary"); exit(1); } if (stat(path, &sb) == 0) return path; free(path); } fprintf(stderr, "Failed to find %s\n", lib); fprintf(stderr, "Tried directories:\n"); for (int i = 0; lib_dirs[i]; i++) { fprintf(stderr, "%s\n" , lib_dirs[i]); } exit(1); return NULL; } static void env_resolve_append_lib_path(const char *var, const char *lib) { char *path = resolve_gputop_lib(lib); const char *cur = getenv(var); list_resource(lib, path); if (cur) { char *val; asprintf(&val, "%s:%s", cur, path); setenv(var, val, true); free(val); } else setenv(var, path, true); } static void print_gputop_env_vars(void) { if (getenv("GPUTOP_FAKE_MODE")) fprintf(stderr, "GPUTOP_FAKE_MODE=%s \\\n", getenv("GPUTOP_FAKE_MODE")); #ifdef SUPPORT_GL if (getenv("GPUTOP_GL_LIBRARY")) fprintf(stderr, "GPUTOP_GL_LIBRARY=%s \\\n", getenv("GPUTOP_GL_LIBRARY")); if (getenv("GPUTOP_EGL_LIBRARY")) fprintf(stderr, "GPUTOP_EGL_LIBRARY=%s \\\n", getenv("GPUTOP_EGL_LIBRARY")); if (getenv("GPUTOP_GL_DEBUG_CONTEXT")) fprintf(stderr, "GPUTOP_GL_DEBUG_CONTEXT=%s \\\n", getenv("GPUTOP_GL_DEBUG_CONTEXT")); if (getenv("GPUTOP_GL_SCISSOR_TEST")) fprintf(stderr, "GPUTOP_GL_SCISSOR_TEST=%s \\\n", getenv("GPUTOP_GL_SCISSOR_TEST")); #endif if (getenv("GPUTOP_MODE")) fprintf(stderr, "GPUTOP_MODE=%s \\\n", getenv("GPUTOP_MODE")); if (getenv("GPUTOP_WEB_ROOT")) fprintf(stderr, "GPUTOP_WEB_ROOT=%s \\\n", getenv("GPUTOP_WEB_ROOT")); } static char * find(const char *parent, const char * const *options) { for (int i = 0; options[i]; i++) { struct stat sb; char *path = NULL; if (asprintf(&path, "%s/%s", parent, options[i]) < 0) { perror("Failed to format gputop-system path"); exit(1); } if (stat(path, &sb) == 0) return path; free(path); } return NULL; } static char * get_gputop_system_path(void) { const char *bin_dir = get_bin_dir(); const char *options[] = { ".libs/lt-gputop-system", ".libs/gputop-system", "gputop-system", NULL }; char *path = find(bin_dir, options); if (!path) { fprintf(stderr, "Failed to find gputop-system program\n"); exit(1); } return path; fprintf(stderr, "Failed to find gputop-system program\n"); exit(1); } #ifdef ENABLE_WEBUI /* See if gputop is being run from a source/build directory and set * the GPUTOP_WEB_ROOT environment accordingly if so, to avoid * neeing to run make install during development/testing... */ static void setup_web_root_env(void) { const char *bin_dir = get_bin_dir(); char dir[1024]; char *prefix; const char *options[] = { "gputop-webui/index.html", "share/remote/index.html", NULL }; char *path; char *root; if (getenv("GPUTOP_WEB_ROOT")) return; strncpy(dir, bin_dir, sizeof(dir)); prefix = dirname(dir); path = find(prefix, options); if (!path) { fprintf(stderr, "Failed to find web assets root path\n"); exit(1); } root = dirname(path); setenv("GPUTOP_WEB_ROOT", root, 1); list_resource("web ui assets", root); free(path); } #endif int main (int argc, char **argv) { int opt; bool dry_run = false; bool disable_ioctl = false; #define LIB_GL_OPT (CHAR_MAX + 1) #define LIB_EGL_OPT (CHAR_MAX + 2) #define DEBUG_CTX_OPT (CHAR_MAX + 3) #define DRY_RUN_OPT (CHAR_MAX + 4) #define DISABLE_IOCTL_OPT (CHAR_MAX + 5) #define FAKE_OPT (CHAR_MAX + 6) #define GPUTOP_SCISSOR_TEST (CHAR_MAX + 7) #define PORT_OPT (CHAR_MAX + 8) #define DISABLE_OACONFIG (CHAR_MAX + 9) /* The initial '+' means that getopt will stop looking for * options after the first non-option argument. */ const char *short_options="+h"; const struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"dry-run", no_argument, 0, DRY_RUN_OPT}, {"fake", no_argument, 0, FAKE_OPT}, {"disable-ioctl-intercept", optional_argument, 0, DISABLE_IOCTL_OPT}, {"disable-oaconfig", optional_argument, 0, DISABLE_OACONFIG}, #ifdef SUPPORT_GL {"libgl", optional_argument, 0, LIB_GL_OPT}, {"libegl", optional_argument, 0, LIB_EGL_OPT}, {"debug-gl-context", no_argument, 0, DEBUG_CTX_OPT}, {"enable-gl-scissor-test", optional_argument, 0, GPUTOP_SCISSOR_TEST}, #endif {"port", required_argument, 0, PORT_OPT}, {0, 0, 0, 0} }; char *ld_preload_path; char *gputop_system_args[] = { get_gputop_system_path(), NULL }; char **args = argv; char prog_name_buf[128]; const char *prog_name = NULL; int err; int i; while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) { switch (opt) { case 'h': usage(); return 0; case DRY_RUN_OPT: dry_run = true; break; case FAKE_OPT: setenv("GPUTOP_FAKE_MODE", "1", true); break; case DISABLE_IOCTL_OPT: disable_ioctl = true; break; case DISABLE_OACONFIG: setenv("GPUTOP_DISABLE_OACONFIG", "1", true); break; #ifdef SUPPORT_GL case LIB_GL_OPT: setenv("GPUTOP_GL_LIBRARY", optarg, true); break; case LIB_EGL_OPT: setenv("GPUTOP_EGL_LIBRARY", optarg, true); break; case DEBUG_CTX_OPT: setenv("GPUTOP_GL_DEBUG_CONTEXT", "1", true); break; case GPUTOP_SCISSOR_TEST: setenv("GPUTOP_GL_SCISSOR_TEST", "1", true); break; #endif case PORT_OPT: setenv("GPUTOP_PORT", optarg, true); break; default: fprintf(stderr, "Internal error: " "unexpected getopt value: %d\n", opt); exit (1); } } if (optind >= argc) { /* If no program is given then launch a dummy "test * application" so gputop can also be used for analysing * system wide metrics. */ args = gputop_system_args; optind = 0; argc = 1; } if (!disable_ioctl) env_resolve_append_lib_path("LD_PRELOAD", "libgputop.so"); #ifdef SUPPORT_GL env_resolve_append_lib_path("LD_PRELOAD", "libfakeGL.so"); if (!getenv("GPUTOP_GL_LIBRARY")) { bool found = resolve_lib_path_for_env("libGL.so.1", "glClear", "GPUTOP_GL_LIBRARY"); if (!found) { fprintf(stderr, "Could not resolve a path for the system libGL.so library\n"); exit(0); } } if (!getenv("GPUTOP_EGL_LIBRARY")) resolve_lib_path_for_env("libEGL.so.1", "eglGetDisplay", "GPUTOP_EGL_LIBRARY"); #endif #ifdef ENABLE_WEBUI setup_web_root_env(); #endif if (n_resources) { fprintf(stderr, "Resources found:\n"); for (int i = 0; resource_locations[i]; i++) fprintf(stderr, " %s\n", resource_locations[i]); } /* * Print out the environment that we are setting up... */ if (dry_run) fprintf(stderr, "\nWould run:\n\n"); else fprintf(stderr, "\nEffectively running:\n\n"); ld_preload_path = getenv("LD_PRELOAD"); if (ld_preload_path) fprintf(stderr, "LD_PRELOAD=%s \\\n", ld_preload_path); print_gputop_env_vars(); for (i = optind; i < argc; i++) fprintf(stderr, "%s ", args[i]); fprintf(stderr, "\n\n"); fprintf(stderr, "NOTE: The use of LD_PRELOAD makes running gdb awkward. Either attach with\n"); strncpy(prog_name_buf, args[optind], sizeof(prog_name_buf)); prog_name = basename(prog_name_buf); fprintf(stderr, "gdb --pid=`pidof %s` or run like:\n\n", prog_name); print_gputop_env_vars(); if (ld_preload_path) fprintf(stderr, "gdb -ex \"set exec-wrapper env 'LD_PRELOAD=%s'\" --args \\\n", ld_preload_path); else fprintf(stderr, "gdb --args \\\n"); for (i = optind; i < argc; i++) fprintf(stderr, "%s ", args[i]); fprintf(stderr, "\n\n"); fprintf(stderr, "Valgrind can be run like:\n\n"); if (ld_preload_path) fprintf(stderr, "LD_PRELOAD=%s \\\n", ld_preload_path); print_gputop_env_vars(); fprintf(stderr, "valgrind --log-file=valgrind-log.txt \\\n"); for (i = optind; i < argc; i++) fprintf(stderr, "%s ", args[i]); fprintf(stderr, "\n\n"); if (!dry_run) { execvp(args[optind], &args[optind]); err = errno; fprintf(stderr, "gputop: Failed to run GL application: \n\n" " "); for (i = optind; i < argc; i++) fprintf(stderr, "%s ", args[i]); fprintf(stderr, "\n\n%s\n", strerror(err)); } return 0; } ================================================ FILE: server/gputop-mainloop.h ================================================ /* * GPU Top * * Copyright (C) 2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include extern uv_loop_t *gputop_mainloop; void gputop_mainloop_quit_idle_cb(uv_idle_t *idle); ================================================ FILE: server/gputop-ncurses.c ================================================ /* * GPU Top * * Copyright (C) 2014,2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include /* NB: We use a portable stdatomic.h, so we don't depend on a recent compiler... */ #include "stdatomic.h" #include "gputop-perf.h" #include "gputop-mainloop.h" #include "gputop-util.h" #include "gputop-sysutil.h" #include "gputop-server.h" #include "gputop-log.h" static uv_timer_t fake_timer; static pthread_t server_thread_id; uv_loop_t *gputop_mainloop; static void exit_fake_mode_cb(uv_timer_t *timer) { exit(0); } void gputop_mainloop_quit_idle_cb(uv_idle_t *idle) { fprintf(stderr, "%s\n", (char *)idle->data); fprintf(stderr, "\n"); _exit(EXIT_FAILURE); } static void * run(void *arg) { gputop_mainloop = uv_loop_new(); if (!gputop_server_run()) _exit(EXIT_FAILURE); if (gputop_fake_mode && gputop_get_bool_env("GPUTOP_TRAVIS_MODE")) { uv_timer_init(gputop_mainloop, &fake_timer); uv_timer_start(&fake_timer, exit_fake_mode_cb, 10000, 10000); } uv_run(gputop_mainloop, UV_RUN_DEFAULT); gputop_perf_free(); return 0; } __attribute__((constructor)) void gputop_init(void) { pthread_attr_t attrs; gputop_perf_initialize(); pthread_attr_init(&attrs); pthread_create(&server_thread_id, &attrs, run, NULL); } ================================================ FILE: server/gputop-perf.c ================================================ /* * GPU Top * * Copyright (C) 2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "dev/gen_device_info.h" #include "gputop-util.h" #include "gputop-sysutil.h" #include "gputop-mainloop.h" #include "gputop-log.h" #include "gputop-perf.h" #include "gputop-oa-metrics.h" #include "gputop-cpu.h" #include "gputop-gens-metrics.h" #include "util/bitscan.h" #include "util/macros.h" #include "util/ralloc.h" /* Samples read() from i915 perf */ struct oa_sample { struct drm_i915_perf_record_header header; uint8_t oa_report[]; }; #define MAX_I915_PERF_OA_SAMPLE_SIZE (8 + /* drm_i915_perf_record_header */ \ 256) /* raw OA counter snapshot */ #define TAKEN(HEAD, TAIL, POT_SIZE) (((HEAD) - (TAIL)) & (POT_SIZE - 1)) /* Note: this will equate to 0 when the buffer is exactly full... */ #define REMAINING(HEAD, TAIL, POT_SIZE) (POT_SIZE - TAKEN (HEAD, TAIL, POT_SIZE)) #if defined(__i386__) #define rmb() __asm__ volatile("lock; addl $0,0(%%esp)" ::: "memory") #define mb() __asm__ volatile("lock; addl $0,0(%%esp)" ::: "memory") #endif #if defined(__x86_64__) #define rmb() __asm__ volatile("lfence" ::: "memory") #define mb() __asm__ volatile("mfence" ::: "memory") #endif /* Allow building for a more recent kernel than the system headers * correspond too... */ #ifndef PERF_RECORD_DEVICE #define PERF_RECORD_DEVICE 14 #endif #ifndef PERF_FLAG_FD_CLOEXEC #define PERF_FLAG_FD_CLOEXEC (1UL << 3) /* O_CLOEXEC */ #endif /* attr.config */ struct intel_device { uint32_t device; uint32_t subsystem_device; uint32_t subsystem_vendor; }; bool gputop_fake_mode = false; static bool gputop_disable_oaconfig = false; static struct intel_device intel_dev; static unsigned int page_size; struct gputop_gen *gen_metrics; struct array *gputop_perf_oa_supported_metric_set_uuids; static struct perf_oa_user *gputop_perf_current_user; static struct gputop_devinfo gputop_devinfo; static int drm_fd = -1; static int drm_card = -1; static struct list_head ctx_handles_list; /******************************************************************************/ /* Handle restarting ioctl if interrupted... */ static int perf_ioctl(int fd, unsigned long request, void *arg) { int ret; do { ret = ioctl(fd, request, arg); } while (ret == -1 && (errno == EINTR || errno == EAGAIN)); return ret; } static bool sysfs_card_read(const char *file, uint64_t *value) { char buf[512]; snprintf(buf, sizeof(buf), "/sys/class/drm/card%d/%s", drm_card, file); return gputop_read_file_uint64(buf, value); } static bool kernel_has_dynamic_config_support(int fd) { if (gputop_disable_oaconfig) return false; list_for_each_entry(struct gputop_metric_set, metric_set, &gen_metrics->metric_sets, link) { struct drm_i915_perf_oa_config config; char config_path[256]; uint32_t mux_regs[] = { 0x9888 /* NOA_WRITE */, 0x0 }; uint64_t config_id; snprintf(config_path, sizeof(config_path), "metrics/%s/id", metric_set->hw_config_guid); if (sysfs_card_read(config_path, &config_id) && config_id != 1) continue; memset(&config, 0, sizeof(config)); memcpy(config.uuid, metric_set->hw_config_guid, sizeof(config.uuid)); config.n_mux_regs = 1; config.mux_regs_ptr = (uintptr_t) mux_regs; if (ioctl(fd, DRM_IOCTL_I915_PERF_REMOVE_CONFIG, &config_id) < 0 && errno == ENOENT) return true; } return false; } static const struct gputop_metric_set * get_test_metric_set(void) { list_for_each_entry(struct gputop_metric_set, metric_set, &gen_metrics->metric_sets, link) { if (!strcmp(metric_set->symbol_name, "TestOa")) return metric_set; } return NULL; } static bool kernel_supports_open_property(uint64_t prop, uint64_t value) { const struct gputop_metric_set *metric_set = get_test_metric_set(); struct drm_i915_perf_open_param param; uint64_t properties[DRM_I915_PERF_PROP_MAX * 2]; int p = 0, stream_fd; if (gputop_fake_mode || !metric_set) return false; memset(¶m, 0, sizeof(param)); param.flags = 0; param.flags |= I915_PERF_FLAG_FD_CLOEXEC; param.flags |= I915_PERF_FLAG_FD_NONBLOCK; properties[p++] = DRM_I915_PERF_PROP_SAMPLE_OA; properties[p++] = true; properties[p++] = DRM_I915_PERF_PROP_OA_METRICS_SET; properties[p++] = metric_set->perf_oa_metrics_set; properties[p++] = DRM_I915_PERF_PROP_OA_FORMAT; properties[p++] = metric_set->perf_oa_format; properties[p++] = DRM_I915_PERF_PROP_OA_EXPONENT; properties[p++] = 5; properties[p++] = DRM_I915_PERF_PROP_CTX_HANDLE; properties[p++] = 999; /* invalid on purpose */ properties[p++] = prop; properties[p++] = value; param.properties_ptr = (uintptr_t)properties; param.num_properties = p / 2; stream_fd = perf_ioctl(drm_fd, DRM_IOCTL_I915_PERF_OPEN, ¶m); assert(stream_fd == -1); return errno == ENOENT; } bool gputop_perf_kernel_has_i915_oa_cpu_timestamps(void) { return kernel_supports_open_property(DRM_I915_PERF_PROP_SAMPLE_SYSTEM_TS, true); } bool gputop_perf_kernel_has_i915_oa_gpu_timestamps(void) { return kernel_supports_open_property(DRM_I915_PERF_PROP_SAMPLE_GPU_TS, true); } bool gputop_add_ctx_handle(int ctx_fd, uint32_t ctx_id) { struct ctx_handle *handle = xmalloc0(sizeof(*handle)); if (!handle) { return false; } handle->id = ctx_id; handle->fd = ctx_fd; list_addtail(&handle->link, &ctx_handles_list); return true; } bool gputop_remove_ctx_handle(uint32_t ctx_id) { list_for_each_entry(struct ctx_handle, ctx, &ctx_handles_list, link) { if (ctx->id == ctx_id) { list_del(&ctx->link); free(ctx); return true; } } return false; } struct ctx_handle *get_first_available_ctx(char **error) { struct ctx_handle *ctx = NULL; ctx = list_first_entry(&ctx_handles_list, struct ctx_handle, link); if (!ctx) { int ret = asprintf(error, "Error unable to find a context\n"); (void) ret; } return ctx; } struct ctx_handle *lookup_ctx_handle(uint32_t ctx_id) { list_for_each_entry(struct ctx_handle, ctx, &ctx_handles_list, link) { if (ctx->id == ctx_id) return ctx; } return NULL; } static long perf_event_open (struct perf_event_attr *hw_event, pid_t pid, int cpu, int group_fd, unsigned long flags) { return syscall(__NR_perf_event_open, hw_event, pid, cpu, group_fd, flags); } static void perf_ready_cb(uv_poll_t *poll, int status, int events) { struct gputop_perf_stream *stream = poll->data; if (stream->ready_cb) stream->ready_cb(stream); } static void perf_fake_ready_cb(uv_timer_t *poll) { struct gputop_perf_stream *stream = poll->data; if (stream->ready_cb) stream->ready_cb(stream); } void gputop_perf_stream_ref(struct gputop_perf_stream *stream) { stream->ref_count++; } /* Stream closing is split up to allow for the closure of * uv poll or timer handles to happen via the mainloop, * via uv_close() before we finish up here... */ static void finish_stream_close(struct gputop_perf_stream *stream) { switch(stream->type) { case GPUTOP_STREAM_PERF: if (stream->fd > 0) { if (stream->perf.mmap_page) { munmap(stream->perf.mmap_page, stream->perf.buffer_size + page_size); stream->perf.mmap_page = NULL; stream->perf.buffer = NULL; stream->perf.buffer_size = 0; } if (stream->perf.header_buf.offsets) { free(stream->perf.header_buf.offsets); stream->perf.header_buf.offsets = NULL; } close(stream->fd); stream->fd = -1; server_dbg("closed perf stream\n"); } break; case GPUTOP_STREAM_I915_PERF: for (int i = 0; i < ARRAY_SIZE(stream->oa.bufs); i++) { if (stream->oa.bufs[i]) { free(stream->oa.bufs[i]); stream->oa.bufs[i] = NULL; } } if (stream->fd == -1) server_dbg("closed i915 fake perf stream\n"); else if (stream->fd > 0) { close(stream->fd); stream->fd = -1; server_dbg("closed i915 perf stream\n"); } break; case GPUTOP_STREAM_CPU: free(stream->cpu.stats_buf); stream->cpu.stats_buf = NULL; server_dbg("closed cpu stats stream\n"); break; } stream->closed = true; stream->on_close_cb(stream); } static void stream_handle_closed_cb(uv_handle_t *handle) { struct gputop_perf_stream *stream = handle->data; if (--(stream->n_closing_uv_handles) == 0) finish_stream_close(stream); } void gputop_perf_stream_close(struct gputop_perf_stream *stream, void (*on_close_cb)(struct gputop_perf_stream *stream)) { stream->on_close_cb = on_close_cb; /* First we close any libuv handles before closing anything else in * stream_handle_closed_cb()... */ switch(stream->type) { case GPUTOP_STREAM_PERF: if (stream->fd >= 0) { uv_close((uv_handle_t *)&stream->fd_poll, stream_handle_closed_cb); stream->n_closing_uv_handles++; } break; case GPUTOP_STREAM_I915_PERF: if (stream->fd == -1) { uv_close((uv_handle_t *)&stream->fd_timer, stream_handle_closed_cb); stream->n_closing_uv_handles++; } if (stream->fd >= 0) { uv_close((uv_handle_t *)&stream->fd_poll, stream_handle_closed_cb); stream->n_closing_uv_handles++; } break; case GPUTOP_STREAM_CPU: uv_close((uv_handle_t *)&stream->cpu.sample_timer, stream_handle_closed_cb); stream->n_closing_uv_handles++; break; } if (!stream->n_closing_uv_handles) finish_stream_close(stream); } void gputop_perf_stream_unref(struct gputop_perf_stream *stream) { if (--(stream->ref_count) == 0) { /* gputop_perf_stream_close() must have been called before the * last reference is dropped... */ assert(stream->closed); if (stream->user.destroy_cb) stream->user.destroy_cb(stream); if (stream->user.data) free(stream->user.data); stream->user.data = NULL; free(stream); server_dbg("freed gputop-perf stream\n"); } } struct gputop_perf_stream * gputop_open_i915_perf_oa_stream(struct gputop_metric_set *metric_set, int period_exponent, struct ctx_handle *ctx, bool cpu_timestamps, bool gpu_timestamps, void (*ready_cb)(struct gputop_perf_stream *), bool overwrite, char **error) { struct gputop_perf_stream *stream; struct drm_i915_perf_open_param param; int stream_fd = -1; int oa_stream_fd = drm_fd; if (!gputop_fake_mode) { uint64_t properties[DRM_I915_PERF_PROP_MAX * 2]; int p = 0; memset(¶m, 0, sizeof(param)); param.flags = 0; param.flags |= I915_PERF_FLAG_FD_CLOEXEC; param.flags |= I915_PERF_FLAG_FD_NONBLOCK; properties[p++] = DRM_I915_PERF_PROP_SAMPLE_OA; properties[p++] = true; properties[p++] = DRM_I915_PERF_PROP_OA_METRICS_SET; properties[p++] = metric_set->perf_oa_metrics_set; properties[p++] = DRM_I915_PERF_PROP_OA_FORMAT; properties[p++] = metric_set->perf_oa_format; properties[p++] = DRM_I915_PERF_PROP_OA_EXPONENT; properties[p++] = period_exponent; if (ctx) { properties[p++] = DRM_I915_PERF_PROP_CTX_HANDLE; properties[p++] = ctx->id; // N.B The file descriptor that was used to create the context, // _must_ be same as the one we use to open the per-context stream. // Since in the kernel we lookup the intel_context based on the ctx // id and the fd that was used to open the stream, so if there is a // mismatch between the file descriptors for the stream and the // context creation then the kernel will simply fail with the // lookup. oa_stream_fd = ctx->fd; dbg("opening per context i915 perf stream: fd = %d, ctx=%u\n", ctx->fd, ctx->id); } if (cpu_timestamps) { properties[p++] = DRM_I915_PERF_PROP_SAMPLE_SYSTEM_TS; properties[p++] = true; } if (gpu_timestamps) { properties[p++] = DRM_I915_PERF_PROP_SAMPLE_GPU_TS; properties[p++] = true; } param.properties_ptr = (uintptr_t)properties; param.num_properties = p / 2; stream_fd = perf_ioctl(oa_stream_fd, DRM_IOCTL_I915_PERF_OPEN, ¶m); if (stream_fd == -1) { int ret = asprintf(error, "Error opening i915 perf OA event: %m\n"); (void) ret; return NULL; } } stream = xmalloc0(sizeof(*stream)); stream->type = GPUTOP_STREAM_I915_PERF; stream->ref_count = 1; stream->metric_set = metric_set; stream->ready_cb = ready_cb; stream->per_ctx_mode = ctx != NULL; stream->fd = stream_fd; if (gputop_fake_mode) { stream->start_time = gputop_get_time(); stream->prev_clocks = gputop_get_time(); stream->period = 80 * (2 << period_exponent); stream->prev_timestamp = gputop_get_time(); } /* We double buffer the samples we read from the kernel so * we can maintain a stream->last pointer for calculating * counter deltas */ stream->oa.buf_sizes = (MAX_I915_PERF_OA_SAMPLE_SIZE + (cpu_timestamps ? 8 : 0) + (gpu_timestamps ? 8 : 0)) * 100; stream->oa.bufs[0] = xmalloc0(stream->oa.buf_sizes); stream->oa.bufs[1] = xmalloc0(stream->oa.buf_sizes); stream->overwrite = overwrite; if (overwrite) { #warning "TODO: support flight-recorder mode" assert(0); } stream->fd_poll.data = stream; stream->fd_timer.data = stream; if (gputop_fake_mode) { uv_timer_init(gputop_mainloop, &stream->fd_timer); uv_timer_start(&stream->fd_timer, perf_fake_ready_cb, 1000, 1000); } else { uv_poll_init(gputop_mainloop, &stream->fd_poll, stream->fd); uv_poll_start(&stream->fd_poll, UV_READABLE, perf_ready_cb); } return stream; } struct gputop_perf_stream * gputop_perf_open_tracepoint(int pid, int cpu, uint64_t id, size_t trace_struct_size, size_t perf_buffer_size, void (*ready_cb)(struct gputop_perf_stream *), bool overwrite, char **error) { struct gputop_perf_stream *stream; struct perf_event_attr attr; int event_fd; uint8_t *mmap_base; int expected_max_samples; size_t sample_size = 0; memset(&attr, 0, sizeof(attr)); attr.size = sizeof(attr); attr.type = PERF_TYPE_TRACEPOINT; attr.config = id; attr.sample_type = PERF_SAMPLE_RAW | PERF_SAMPLE_TIME; attr.sample_period = 1; //attr.wakeup_events = 1; attr.watermark = true; attr.wakeup_watermark = perf_buffer_size / 4; attr.clockid = CLOCK_MONOTONIC; attr.use_clockid = true; event_fd = perf_event_open(&attr, pid, cpu, -1, /* group fd */ PERF_FLAG_FD_CLOEXEC); /* flags */ if (event_fd == -1) { int ret = asprintf(error, "Error opening perf tracepoint event: %m\n"); (void) ret; return NULL; } /* NB: A read-write mapping ensures the kernel will stop writing data when * the buffer is full, and will report samples as lost. */ mmap_base = mmap(NULL, perf_buffer_size + page_size, PROT_READ | PROT_WRITE, MAP_SHARED, event_fd, 0); if (mmap_base == MAP_FAILED) { int ret = asprintf(error, "Error mapping circular buffer, %m\n"); (void) ret; close (event_fd); return NULL; } stream = xmalloc0(sizeof(*stream)); stream->type = GPUTOP_STREAM_PERF; stream->ref_count = 1; stream->fd = event_fd; stream->perf.buffer = mmap_base + page_size; stream->perf.buffer_size = perf_buffer_size; stream->perf.mmap_page = (void *)mmap_base; stream->ready_cb = ready_cb; sample_size = sizeof(struct perf_event_header) + 8 /* _TIME */ + trace_struct_size; /* _RAW */ expected_max_samples = (stream->perf.buffer_size / sample_size) * 1.2; memset(&stream->perf.header_buf, 0, sizeof(stream->perf.header_buf)); stream->overwrite = overwrite; if (overwrite) { stream->perf.header_buf.len = expected_max_samples; stream->perf.header_buf.offsets = xmalloc(sizeof(uint32_t) * expected_max_samples); } stream->fd_poll.data = stream; uv_poll_init(gputop_mainloop, &stream->fd_poll, stream->fd); uv_poll_start(&stream->fd_poll, UV_READABLE, perf_ready_cb); return stream; } struct gputop_perf_stream * gputop_perf_open_generic_counter(int pid, int cpu, uint64_t type, uint64_t config, size_t perf_buffer_size, void (*ready_cb)(uv_poll_t *poll, int status, int events), bool overwrite, char **error) { struct gputop_perf_stream *stream; struct perf_event_attr attr; int event_fd; uint8_t *mmap_base; int expected_max_samples; size_t sample_size = 0; memset(&attr, 0, sizeof(attr)); attr.size = sizeof(attr); attr.type = type; attr.config = config; attr.sample_type = PERF_SAMPLE_READ | PERF_SAMPLE_TIME; attr.sample_period = 1; attr.watermark = true; attr.wakeup_watermark = perf_buffer_size / 4; event_fd = perf_event_open(&attr, pid, cpu, -1, /* group fd */ PERF_FLAG_FD_CLOEXEC); /* flags */ if (event_fd == -1) { int ret = asprintf(error, "Error opening perf event: %m\n"); (void) ret; return NULL; } /* NB: A read-write mapping ensures the kernel will stop writing data when * the buffer is full, and will report samples as lost. */ mmap_base = mmap(NULL, perf_buffer_size + page_size, PROT_READ | PROT_WRITE, MAP_SHARED, event_fd, 0); if (mmap_base == MAP_FAILED) { int ret = asprintf(error, "Error mapping circular buffer, %m\n"); (void) ret; close (event_fd); return NULL; } stream = xmalloc0(sizeof(*stream)); stream->type = GPUTOP_STREAM_PERF; stream->ref_count = 1; stream->fd = event_fd; stream->perf.buffer = mmap_base + page_size; stream->perf.buffer_size = perf_buffer_size; stream->perf.mmap_page = (void *)mmap_base; sample_size = sizeof(struct perf_event_header) + 8; /* _TIME */ expected_max_samples = (stream->perf.buffer_size / sample_size) * 1.2; memset(&stream->perf.header_buf, 0, sizeof(stream->perf.header_buf)); stream->overwrite = overwrite; if (overwrite) { stream->perf.header_buf.len = expected_max_samples; stream->perf.header_buf.offsets = xmalloc(sizeof(uint32_t) * expected_max_samples); } stream->fd_poll.data = stream; uv_poll_init(gputop_mainloop, &stream->fd_poll, stream->fd); uv_poll_start(&stream->fd_poll, UV_READABLE, ready_cb); return stream; } static void log_cpu_stats_cb(uv_timer_t *timer) { struct gputop_perf_stream *stream = timer->data; if (stream->cpu.stats_buf_pos < stream->cpu.stats_buf_len) { struct cpu_stat *stats = stream->cpu.stats_buf + stream->cpu.stats_buf_pos; int n_cpus = gputop_cpu_count(); gputop_cpu_read_stats(stats, n_cpus); stream->cpu.stats_buf_pos += n_cpus; } if (stream->cpu.stats_buf_pos >= stream->cpu.stats_buf_len) { stream->cpu.stats_buf_full = true; if (stream->overwrite) stream->cpu.stats_buf_pos = 0; } } struct gputop_perf_stream * gputop_perf_open_cpu_stats(bool overwrite, uint64_t sample_period_ms) { struct gputop_perf_stream *stream; int n_cpus = gputop_cpu_count(); stream = xmalloc0(sizeof(*stream)); stream->type = GPUTOP_STREAM_CPU; stream->ref_count = 1; stream->cpu.stats_buf_len = MAX(10, 1000 / sample_period_ms); stream->cpu.stats_buf = xmalloc(stream->cpu.stats_buf_len * sizeof(struct cpu_stat) * n_cpus); stream->cpu.stats_buf_pos = 0; stream->overwrite = overwrite; stream->cpu.sample_timer.data = stream; uv_timer_init(gputop_mainloop, &stream->cpu.sample_timer); uv_timer_start(&stream->cpu.sample_timer, log_cpu_stats_cb, sample_period_ms, sample_period_ms); return stream; } static void devinfo_build_topology(const struct gen_device_info *devinfo, struct gputop_devtopology *topology) { int s, ss, eug; int slice_stride, subslice_stride; topology->max_slices = devinfo->num_slices; topology->max_subslices = devinfo->num_subslices[0]; if (devinfo->is_haswell) topology->max_eus_per_subslice = 10; else topology->max_eus_per_subslice = 8; // TODO. subslice_stride = DIV_ROUND_UP(topology->max_eus_per_subslice, 8); slice_stride = subslice_stride * topology->max_subslices; for (s = 0; s < devinfo->num_slices; s++) { topology->slices_mask[0] |= 1U << s; for (ss = 0; ss < devinfo->num_subslices[s]; ss++) { /* Assuming we have never more than 8 subslices. */ topology->subslices_mask[s] |= 1U << ss; for (eug = 0; eug < subslice_stride; eug++) { topology->eus_mask[s * slice_stride + ss * subslice_stride + eug] = (((1UL << topology->max_eus_per_subslice) - 1) >> (eug * 8)) & 0xff; } } } } static bool fill_topology_from_masks(struct gputop_devtopology *topology, uint32_t s_mask, uint32_t ss_mask, uint32_t n_eus) { int n_slices = 0, n_subslices = 0; int s, ss, eug; memset(topology->slices_mask, 0, sizeof(topology->slices_mask)); topology->slices_mask[0] = s_mask; topology->max_slices = util_last_bit(s_mask); n_slices = __builtin_popcount(s_mask); memset(topology->subslices_mask, 0, sizeof(topology->subslices_mask)); for (s = 0; s < util_last_bit(s_mask); s++) { int subslice_stride = DIV_ROUND_UP(ss_mask, 8); for (ss = 0; ss < subslice_stride; ss++) { topology->subslices_mask[s * subslice_stride + ss] = (ss_mask >> (ss * 8)) & 0xff; } } topology->max_subslices = util_last_bit(ss_mask); n_subslices = __builtin_popcount(ss_mask); int subslice_stride = DIV_ROUND_UP(n_eus / (topology->max_slices * topology->max_subslices), 8); int slice_stride = subslice_stride * topology->max_subslices; int n_eus_per_subslice = n_eus / (n_slices * n_subslices); int subslice_slice_stride = DIV_ROUND_UP(topology->max_subslices, 8); topology->max_eus_per_subslice = 8 * DIV_ROUND_UP(n_eus_per_subslice, 8); memset(topology->eus_mask, 0, sizeof(topology->eus_mask)); for (s = 0; s < topology->max_slices; s++) { for (ss = 0; ss < topology->max_subslices; ss++) { if (topology->subslices_mask[s * subslice_slice_stride + ss / 8] & (1UL << (ss % 8))) { for (eug = 0; eug < subslice_stride; eug++) { topology->eus_mask[s * slice_stride + ss * subslice_stride + eug] = (((1UL << n_eus_per_subslice) - 1) >> (eug * 8)) & 0xff; } } } } return true; } static bool gputop_override_topology(struct gputop_devtopology *topology) { long s_mask = 0, ss_mask = 0, n_eus = 0; const char *s_s_mask = getenv("GPUTOP_TOPOLOGY_OVERRIDE"); if (!s_s_mask) return false; s_mask = strtol(s_s_mask, NULL, 0); const char *s_ss_mask = strstr(s_s_mask, ","); if (!s_ss_mask) goto invalid; s_ss_mask++; ss_mask = strtol(s_ss_mask, NULL, 0); const char *s_n_eus = strstr(s_ss_mask, ","); if (!s_n_eus) goto invalid; s_n_eus++; n_eus = strtol(s_n_eus, NULL, 0); if (s_mask == 0 || ss_mask == 0 || n_eus == 0) goto invalid; fprintf(stderr, "Using topology override: slice_mask=%li subslice=%li n_eus=%li\n", s_mask, ss_mask, n_eus); fill_topology_from_masks(topology, s_mask, ss_mask, n_eus); return true; invalid: fprintf(stderr, "Invalid topology override: slice_mask=%li subslice=%li n_eus=%li\n", s_mask, ss_mask, n_eus); return false; } static bool i915_query_old_slice_masks(int fd, struct gputop_devtopology *topology) { drm_i915_getparam_t gp; int s_mask = 0, ss_mask = 0, n_eus = 0; gp.param = I915_PARAM_SLICE_MASK; gp.value = &s_mask; if (perf_ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp)) return false; gp.param = I915_PARAM_SUBSLICE_MASK; gp.value = &ss_mask; if (perf_ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp)) return false; gp.param = I915_PARAM_EU_TOTAL; gp.value = &n_eus; if (perf_ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp)) return false; fill_topology_from_masks(topology, s_mask, ss_mask, n_eus); return true; } struct gputop_query_topology_info { struct drm_i915_query_topology_info base; char data[512]; }; static void i915_query_topology(int fd, struct gputop_devtopology *topology) { struct drm_i915_query query = {}; struct gputop_query_topology_info topo_info = {}; struct drm_i915_query_item item = { .query_id = DRM_I915_QUERY_TOPOLOGY_INFO, .length = sizeof(topo_info), .data_ptr = (uintptr_t) &topo_info, }; int ret; query.num_items = 1; query.items_ptr = (uintptr_t) &item; ret = perf_ioctl(fd, DRM_IOCTL_I915_QUERY, &query); assert(ret == 0); assert(item.length > 0); topology->max_slices = topo_info.base.max_slices; topology->max_subslices = topo_info.base.max_subslices; topology->max_eus_per_subslice = topo_info.base.max_eus_per_subslice; assert(sizeof(topology->slices_mask) >= topo_info.base.subslice_offset); memcpy(topology->slices_mask, topo_info.data, topo_info.base.subslice_offset); assert(sizeof(topology->subslices_mask) >= (topo_info.base.eu_offset - topo_info.base.subslice_offset)); memcpy(topology->subslices_mask, &topo_info.data[topo_info.base.subslice_offset], topo_info.base.eu_offset - topo_info.base.subslice_offset); assert(sizeof(topology->eus_mask) >= (item.length - topo_info.base.eu_offset)); memcpy(topology->eus_mask, &topo_info.data[topo_info.base.eu_offset], item.length - topo_info.base.eu_offset); } static bool i915_has_query_info(int fd) { struct drm_i915_query_item item = { .query_id = DRM_I915_QUERY_TOPOLOGY_INFO, }; struct drm_i915_query query = { .num_items = 1, .items_ptr = (uintptr_t) &item }; return perf_ioctl(fd, DRM_IOCTL_I915_QUERY, &query) == 0 && item.length > 0; } static void i915_query_engines(int fd, struct gputop_devtopology *topology) { DIR *engines_dir; struct dirent *entry; char path[512]; assert(ARRAY_SIZE(topology->engines) >= I915_ENGINE_CLASS_VIDEO_ENHANCE + 1); snprintf(path, sizeof(path), "/sys/class/drm/card%d/engines", drm_card); engines_dir = opendir(path); if (!engines_dir) return; while ((entry = readdir(engines_dir))) { if (entry->d_type != DT_DIR) continue; uint64_t engine_class = 0; snprintf(path, sizeof(path), "engines/%s/class", entry->d_name); if (!sysfs_card_read(path, &engine_class)) continue; if (engine_class >= ARRAY_SIZE(topology->engines)) continue; topology->engines[engine_class]++; } closedir(engines_dir); } static bool init_dev_info(int fd, uint32_t devid, const struct gen_device_info *devinfo) { struct gputop_devtopology *topology = &gputop_devinfo.topology; memset(&gputop_devinfo, 0, sizeof(gputop_devinfo)); gputop_devinfo.devid = devid; #define SET_NAMES(g, _devname, _prettyname) do { \ strncpy(g.devname, _devname, sizeof(g.devname)); \ strncpy(g.prettyname, _prettyname, sizeof(g.prettyname)); \ } while (0) gputop_devinfo.gen = devinfo->gen; gputop_devinfo.timestamp_frequency = devinfo->timestamp_frequency; topology->n_threads_per_eu = devinfo->num_thread_per_eu; if (gputop_fake_mode) { fill_topology_from_masks(topology, 0x1, 0x1, 8); gputop_devinfo.gt_min_freq = 500; gputop_devinfo.gt_max_freq = 1100; } else { drm_i915_getparam_t gp; int revision, timestamp_frequency; gp.param = I915_PARAM_REVISION; gp.value = &revision; perf_ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp); gputop_devinfo.revision = revision; /* This might not be available on all kernels, save the value * only if the ioctl succeeds. */ gp.param = I915_PARAM_CS_TIMESTAMP_FREQUENCY; gp.value = ×tamp_frequency; if (perf_ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp) == 0) gputop_devinfo.timestamp_frequency = timestamp_frequency; if (!gputop_override_topology(topology)) { if (i915_has_query_info(fd)) { i915_query_topology(fd, topology); i915_query_engines(fd, topology); } else if (!i915_query_old_slice_masks(fd, topology)) devinfo_build_topology(devinfo, topology); } assert(drm_card >= 0); if (!sysfs_card_read("gt_min_freq_mhz", &gputop_devinfo.gt_min_freq)) fprintf(stderr, "Unable to read GT min frequency\n"); if (!sysfs_card_read("gt_max_freq_mhz", &gputop_devinfo.gt_max_freq)) fprintf(stderr, "Unable to read GT max frequency\n"); gputop_devinfo.gt_min_freq *= 1000000; gputop_devinfo.gt_max_freq *= 1000000; } if (devinfo->is_haswell) { SET_NAMES(gputop_devinfo, "hsw", "Haswell"); gen_metrics = gputop_oa_get_metrics_hsw(&gputop_devinfo); } else if (devinfo->is_broadwell) { SET_NAMES(gputop_devinfo, "bdw", "Broadwell"); gen_metrics = gputop_oa_get_metrics_bdw(&gputop_devinfo); } else if (devinfo->is_cherryview) { SET_NAMES(gputop_devinfo, "chv", "Cherryview"); gen_metrics = gputop_oa_get_metrics_chv(&gputop_devinfo); } else if (devinfo->is_skylake) { switch (devinfo->gt) { case 2: SET_NAMES(gputop_devinfo, "sklgt2", "Skylake GT2"); gen_metrics = gputop_oa_get_metrics_sklgt2(&gputop_devinfo); break; case 3: SET_NAMES(gputop_devinfo, "sklgt3", "Skylake GT3"); gen_metrics = gputop_oa_get_metrics_sklgt3(&gputop_devinfo); break; case 4: SET_NAMES(gputop_devinfo, "sklgt4", "Skylake GT4"); gen_metrics = gputop_oa_get_metrics_sklgt4(&gputop_devinfo); break; default: fprintf(stderr, "Unsupported GT%u Skylake System\n", devinfo->gt); return false; } } else if (devinfo->is_broxton) { SET_NAMES(gputop_devinfo, "bxt", "Broxton"); gen_metrics = gputop_oa_get_metrics_bxt(&gputop_devinfo); } else if (devinfo->is_kabylake) { switch (devinfo->gt) { case 2: SET_NAMES(gputop_devinfo, "kblgt2", "Kabylake GT2"); gen_metrics = gputop_oa_get_metrics_kblgt2(&gputop_devinfo); break; case 3: SET_NAMES(gputop_devinfo, "kblgt3", "Kabylake GT3"); gen_metrics = gputop_oa_get_metrics_kblgt3(&gputop_devinfo); break; default: fprintf(stderr, "Unsupported GT%u Kabylake System\n", devinfo->gt); return false; } } else if (devinfo->is_geminilake) { SET_NAMES(gputop_devinfo, "glk", "Geminilake"); gen_metrics = gputop_oa_get_metrics_glk(&gputop_devinfo); } else if (devinfo->is_coffeelake) { switch (devinfo->gt) { case 2: SET_NAMES(gputop_devinfo, "cflgt2", "Coffeelake GT2"); gen_metrics = gputop_oa_get_metrics_cflgt2(&gputop_devinfo); break; case 3: SET_NAMES(gputop_devinfo, "cflgt3", "Coffeelake GT3"); gen_metrics = gputop_oa_get_metrics_cflgt3(&gputop_devinfo); break; default: fprintf(stderr, "Unsupported GT%u Coffeelake System\n", devinfo->gt); return false; } } else if (devinfo->is_cannonlake) { SET_NAMES(gputop_devinfo, "cnl", "Cannonlake"); gen_metrics = gputop_oa_get_metrics_cnl(&gputop_devinfo); } else if (devinfo->is_elkhartlake) { SET_NAMES(gputop_devinfo, "EHL", "Elkhartlake"); gen_metrics = gputop_oa_get_metrics_lkf(&gputop_devinfo); } else if (devinfo->gen == 11) { SET_NAMES(gputop_devinfo, "icl", "Icelake"); gen_metrics = gputop_oa_get_metrics_icl(&gputop_devinfo); } else { fprintf(stderr, "Unknown System\n"); return false; } if (gputop_fake_mode) SET_NAMES(gputop_devinfo, "bdw", "Fake Broadwell Intel device"); else { gputop_devinfo.has_dynamic_configs = kernel_has_dynamic_config_support(fd); } return true; #undef SET_NAMES } static unsigned int read_perf_head(struct perf_event_mmap_page *mmap_page) { unsigned int head = (*(volatile uint64_t *)&mmap_page->data_head); rmb(); return head; } static void write_perf_tail(struct perf_event_mmap_page *mmap_page, unsigned int tail) { /* Make sure we've finished reading all the sample data we * we're consuming before updating the tail... */ mb(); mmap_page->data_tail = tail; } static bool perf_stream_data_pending(struct gputop_perf_stream *stream) { uint64_t head = read_perf_head(stream->perf.mmap_page); uint64_t tail = stream->perf.mmap_page->data_tail; return !!TAKEN(head, tail, stream->perf.buffer_size); } static bool i915_perf_stream_data_pending(struct gputop_perf_stream *stream) { struct pollfd pollfd = { stream->fd, POLLIN, 0 }; int ret; if (gputop_fake_mode) { uint64_t elapsed_time = gputop_get_time() - stream->start_time; if (elapsed_time / stream->period - stream->gen_so_far > 0) return true; else return false; } else { while ((ret = poll(&pollfd, 1, 0)) < 0 && errno == EINTR) ; if (ret == 1 && pollfd.revents & POLLIN) return true; else return false; } } bool gputop_stream_data_pending(struct gputop_perf_stream *stream) { switch (stream->type) { case GPUTOP_STREAM_PERF: return perf_stream_data_pending(stream); case GPUTOP_STREAM_I915_PERF: return i915_perf_stream_data_pending(stream); case GPUTOP_STREAM_CPU: if (stream->cpu.stats_buf_pos == 0 && !stream->cpu.stats_buf_full) return false; else return true; } assert(0); } /* Perf supports a flight recorder mode whereby it won't stop writing * samples once the buffer is full and will instead overwrite old * samples. * * The difficulty with this mode is that because samples don't have a * uniform size, once the head gets trampled we can no longer parse * *any* samples since the location of each sample depends of the * length of the previous. * * Since we are paranoid about wasting memory bandwidth - as such a * common gpu bottleneck - we would rather not resort to copying * samples into another buffer, especially to implement a tracing * feature where higher sampler frequencies are interesting. * * To simplify things to handle the main case we care about where * the perf circular buffer is full of samples (as opposed to * lots of throttle or status records) we can define a fixed number * of pointers to track, given the size of the perf buffer and * known size for samples. These can be tracked in a circular * buffer with fixed size records where overwriting the head isn't * a problem. */ /* * For each update of this buffer we: * * 1) Check what new records have been added: * * * if buf->last_perf_head uninitialized, set it to the perf tail * * foreach new record from buf->last_perf_head to the current perf head: * - check there's room for a new header offset, but if not: * - report an error * - move the tail forward (loosing a record) * - add a header offset to buf->offsets[buf->head] * - buf->head++; * - recognise when the perf head wraps and mark the buffer 'full' * * 2) Optionally parse any of the new records (i.e. before we update * tail) * * Typically we aren't processing the records while tracing, but * beware that if anything does need passing on the fly then it * needs to be done before we update the tail pointer below. * * 3) If buf 'full'; check how much of perf's tail has been eaten: * * * move buf->tail forward to the next offset that is ahead of * perf's (head + header->size) * XXX: we can assert() that we don't overtake buf->head. That * shouldn't be possible if we aren't enabling perf's * overwriting/flight recorder mode. * XXX: Note: we do this after checking for new records so we * don't have to worry about the corner case of eating more * than we previously knew about. * * 4) Set perf's tail to perf's head (i.e. consume everything so that * perf won't block when wrapping around and overwriting old * samples.) */ void gputop_perf_update_header_offsets(struct gputop_perf_stream *stream) { struct gputop_perf_header_buf *hdr_buf = &stream->perf.header_buf; uint8_t *data = stream->perf.buffer; const uint64_t mask = stream->perf.buffer_size - 1; uint64_t perf_head; uint64_t perf_tail; uint32_t buf_head; uint32_t buf_tail; uint32_t n_new = 0; perf_head = read_perf_head(stream->perf.mmap_page); //if (hdr_buf->head == hdr_buf->tail) //perf_tail = hdr_buf->last_perf_head; //else perf_tail = stream->perf.mmap_page->data_tail; #if 0 if (perf_tail > perf_head) { dbg("Unexpected perf tail > head condition\n"); return; } #endif if (perf_head == perf_tail) return; //hdr_buf->last_perf_head = perf_head; buf_head = hdr_buf->head; buf_tail = hdr_buf->tail; #if 1 printf("perf records:\n"); printf("> fd = %d\n", stream->fd); printf("> size = %lu\n", stream->perf.buffer_size); printf("> tail_ptr = %p\n", &stream->perf.mmap_page->data_tail); printf("> head=%"PRIu64"\n", perf_head); printf("> tail=%"PRIu64"\n", (uint64_t)stream->perf.mmap_page->data_tail); printf("> TAKEN=%"PRIu64"\n", (uint64_t)TAKEN(perf_head, stream->perf.mmap_page->data_tail, stream->perf.buffer_size)); printf("> records:\n"); #endif while (TAKEN(perf_head, perf_tail, stream->perf.buffer_size)) { uint64_t perf_offset = perf_tail & mask; const struct perf_event_header *header = (const struct perf_event_header *)(data + perf_offset); n_new++; if (header->size == 0) { dbg("Spurious header size == 0\n"); /* XXX: How should we handle this instead of exiting() */ break; //exit(1); } if (header->size > (perf_head - perf_tail)) { dbg("Spurious header size would overshoot head\n"); /* XXX: How should we handle this instead of exiting() */ break; //exit(1); } /* Once perf wraps, the buffer is full of data and perf starts * to eat its tail, overwriting old data. */ if ((const uint8_t *)header + header->size > data + stream->perf.buffer_size) hdr_buf->full = true; if ((buf_head - buf_tail) == hdr_buf->len) buf_tail++; /* Checking what tail records have been being overwritten by this * new record... * * NB: A record may be split at the end of the buffer * NB: A large record may trample multiple smaller records * NB: it's possible no records have been trampled */ if (hdr_buf->full) { while (1) { uint32_t buf_tail_offset = hdr_buf->offsets[buf_tail % hdr_buf->len]; /* To simplify checking for an overlap, invariably ensure the * buf_tail_offset is ahead of perf, even if it means using a * fake offset beyond the bounds of the buffer... */ if (buf_tail_offset < perf_offset) buf_tail_offset += stream->perf.buffer_size; if ((perf_offset + header->size) < buf_tail_offset) /* nothing eaten */ break; buf_tail++; } } hdr_buf->offsets[buf_head++ % hdr_buf->len] = perf_offset; perf_tail += header->size; } /* Consume all perf records so perf wont be blocked from * overwriting old samples... */ write_perf_tail(stream->perf.mmap_page, perf_head); hdr_buf->head = buf_head; hdr_buf->tail = buf_tail; #if 1 printf("headers update:\n"); printf("n new records = %d\n", n_new); printf("buf len = %d\n", hdr_buf->len); printf("perf head = %"PRIu64"\n", perf_head); printf("perf tail = %"PRIu64"\n", perf_tail); printf("buf head = %"PRIu32"\n", hdr_buf->head); printf("buf tail = %"PRIu32"\n", hdr_buf->tail); if (!hdr_buf->full) { float percentage = (hdr_buf->offsets[(hdr_buf->head - 1) % hdr_buf->len] / (float)stream->perf.buffer_size) * 100.0f; printf("> %d%% full\n", (int)percentage); } else printf("> 100%% full\n"); printf("> n records = %u\n", (hdr_buf->head - hdr_buf->tail)); #endif } void gputop_i915_perf_print_records(struct gputop_perf_stream *stream, uint8_t *buf, int len) { const struct drm_i915_perf_record_header *header; int offset = 0; printf("records:\n"); for (offset = 0; offset < len; offset += header->size) { header = (const struct drm_i915_perf_record_header *)(buf + offset); if (header->size == 0) { printf("Spurious header size == 0\n"); return; } printf("- header size = %d\n", header->size); switch (header->type) { case DRM_I915_PERF_RECORD_OA_BUFFER_LOST: printf("- OA buffer error - all records lost\n"); break; case DRM_I915_PERF_RECORD_OA_REPORT_LOST: printf("- OA report lost\n"); break; case DRM_I915_PERF_RECORD_SAMPLE: { printf("- Sample\n"); break; } default: printf("- Spurious header type = %d\n", header->type); } } } static void read_perf_samples(struct gputop_perf_stream *stream) { dbg("FIXME: read core perf samples"); } struct report_layout { struct drm_i915_perf_record_header header; uint32_t rep_id; uint32_t timest; uint32_t context_id; uint32_t clock_ticks; uint32_t counter_40_lsb[32]; uint32_t agg_counter[4]; uint8_t counter_40_msb[32]; uint32_t bool_custom_counters[16]; }; // Function that generates fake Broadwell report metrics int gputop_perf_fake_read(struct gputop_perf_stream *stream, uint8_t *buf, int buf_length) { struct report_layout *report = (struct report_layout *)buf; struct drm_i915_perf_record_header header; uint32_t timestamp, elapsed_clocks; int i; uint64_t counter; uint64_t elapsed_time = gputop_get_time() - stream->start_time; uint32_t records_to_gen; header.type = DRM_I915_PERF_RECORD_SAMPLE; header.pad = 0; header.size = sizeof(struct report_layout); // Calculate the minimum between records required (in relation to the time elapsed) // and the maximum number of records that can bit in the buffer. if (elapsed_time / stream->period - stream->gen_so_far < buf_length / header.size) records_to_gen = elapsed_time / stream->period - stream->gen_so_far; else records_to_gen = buf_length / header.size; for (i = 0; i < records_to_gen; i++) { int j; uint32_t counter_lsb; uint8_t counter_msb; // Header report->header = header; // Reason / Report ID report->rep_id = 1 << 19; // Timestamp timestamp = stream->period / 80 + stream->prev_timestamp; stream->prev_timestamp = timestamp; report->timest = timestamp; // GPU Clock Ticks elapsed_clocks = stream->period / 2 + stream->prev_clocks; stream->prev_clocks = elapsed_clocks; report->clock_ticks = elapsed_clocks; counter = elapsed_clocks * gputop_devinfo.n_eus; counter_msb = (counter >> 32) & 0xFF; counter_lsb = (uint32_t)counter; // Populate the 40 bit counters for (j = 0; j < 32; j++) { report->counter_40_lsb[j] = counter_lsb; report->counter_40_msb[j] = counter_msb; } // Populate the next 4 Counters for (j = 0; j < 4; j++) report->agg_counter[j] = counter_lsb; // Populate the final 16 boolean & custom counters counter = elapsed_clocks * 2; counter_lsb = (uint32_t)counter; for (j = 0; j < 16; j++) report->bool_custom_counters[j] = counter_lsb; stream->gen_so_far++; report++; } return header.size * records_to_gen; } static void read_i915_perf_samples(struct gputop_perf_stream *stream) { do { int offset = 0; int buf_idx; uint8_t *buf; int count; /* We double buffer reads so we can safely keep a pointer to * our last sample for calculating deltas */ buf_idx = !stream->oa.last_buf_idx; buf = stream->oa.bufs[buf_idx]; if (gputop_fake_mode) count = gputop_perf_fake_read(stream, buf, stream->oa.buf_sizes); else count = read(stream->fd, buf, stream->oa.buf_sizes); if (count < 0) { if (errno == EINTR) continue; else if (errno == EAGAIN) break; else { dbg("Error reading i915 OA event stream %m"); break; } } if (count == 0) break; while (offset < count) { const struct drm_i915_perf_record_header *header = (const struct drm_i915_perf_record_header *)(buf + offset); if (header->size == 0) { dbg("Spurious header size == 0\n"); /* XXX: How should we handle this instead of exiting() */ exit(1); } offset += header->size; switch (header->type) { case DRM_I915_PERF_RECORD_OA_BUFFER_LOST: dbg("i915 perf: OA buffer error - all records lost\n"); break; case DRM_I915_PERF_RECORD_OA_REPORT_LOST: dbg("i915 perf: OA report lost\n"); break; case DRM_I915_PERF_RECORD_SAMPLE: { struct oa_sample *sample = (struct oa_sample *)header; uint8_t *report = sample->oa_report; if (stream->oa.last) gputop_perf_current_user->sample(stream, stream->oa.last, report); stream->oa.last = report; /* track which buffer oa.last points into so our next read * won't clobber it... */ stream->oa.last_buf_idx = buf_idx; break; } default: dbg("i915 perf: Spurious header type = %d\n", header->type); } } } while(1); } void gputop_perf_read_samples(struct gputop_perf_stream *stream) { switch (stream->type) { case GPUTOP_STREAM_PERF: read_perf_samples(stream); return; case GPUTOP_STREAM_I915_PERF: read_i915_perf_samples(stream); return; case GPUTOP_STREAM_CPU: assert(0); return; } assert(0); } static int get_card_for_fd(int fd) { struct stat sb; int mjr, mnr; char buffer[128]; DIR *drm_dir; struct dirent *entry; int retval = -1; if (fstat(fd, &sb)) { gputop_log(GPUTOP_LOG_LEVEL_HIGH, "Failed to stat DRM fd\n", -1); return -1; } mjr = major(sb.st_rdev); mnr = minor(sb.st_rdev); snprintf(buffer, sizeof(buffer), "/sys/dev/char/%d:%d/device/drm", mjr, mnr); drm_dir = opendir(buffer); assert(drm_dir != NULL); while ((entry = readdir(drm_dir))) { if (entry->d_type == DT_DIR && strncmp(entry->d_name, "card", 4) == 0) { retval = strtoull(entry->d_name + 4, NULL, 10); break; } } closedir(drm_dir); return retval; } static uint32_t read_device_param(const char *stem, int id, const char *param) { char *name; int ret = asprintf(&name, "/sys/class/drm/%s%u/device/%s", stem, id, param); uint64_t value; bool success; assert(ret != -1); success = gputop_read_file_uint64(name, &value); free(name); return success ? value : 0; } static int find_intel_render_node(void) { for (int i = 128; i < (128 + 16); i++) { if (read_device_param("renderD", i, "vendor") == 0x8086) return i; } return -1; } static int open_render_node(struct intel_device *dev) { char *name; int ret; int fd; int render = find_intel_render_node(); if (render < 0) return -1; ret = asprintf(&name, "/dev/dri/renderD%u", render); assert(ret != -1); fd = open(name, O_RDWR); free(name); if (fd == -1) return -1; dev->device = read_device_param("renderD", render, "device"); dev->subsystem_device = read_device_param("renderD", render, "subsystem_device"); dev->subsystem_vendor = read_device_param("renderD", render, "subsystem_vendor"); return fd; } static void gputop_reload_userspace_metrics(int fd) { if (!gputop_devinfo.has_dynamic_configs) return; list_for_each_entry(struct gputop_metric_set, metric_set, &gen_metrics->metric_sets, link) { struct drm_i915_perf_oa_config config; char config_path[256]; uint64_t config_id; int ret; snprintf(config_path, sizeof(config_path), "metrics/%s/id", metric_set->hw_config_guid); if (sysfs_card_read(config_path, &config_id)) { if (config_id > 1) perf_ioctl(fd, DRM_IOCTL_I915_PERF_REMOVE_CONFIG, &config_id); else if (config_id == 1) continue; /* Leave the test config untouched */ } memset(&config, 0, sizeof(config)); memcpy(config.uuid, metric_set->hw_config_guid, sizeof(config.uuid)); config.n_mux_regs = metric_set->n_mux_regs; config.mux_regs_ptr = (uintptr_t) metric_set->mux_regs; config.n_boolean_regs = metric_set->n_b_counter_regs; config.boolean_regs_ptr = (uintptr_t) metric_set->b_counter_regs; config.n_flex_regs = metric_set->n_flex_regs; config.flex_regs_ptr = (uintptr_t) metric_set->flex_regs; ret = perf_ioctl(fd, DRM_IOCTL_I915_PERF_ADD_CONFIG, &config); if (ret < 0) fprintf(stderr, "Failed to load %s (%s) metrics set in kernel: %s\n", metric_set->symbol_name, metric_set->hw_config_guid, strerror(errno)); } } static bool gputop_enumerate_metrics_via_sysfs(void) { DIR *metrics_dir; struct dirent *entry; char buffer[128]; uint64_t paranoid = 0; if (!gputop_read_file_uint64("/proc/sys/dev/i915/perf_stream_paranoid", ¶noid)) { fprintf(stderr, "Kernel is missing i915 perf support\n"); return false; } if (getuid() != 0 && paranoid) { fprintf(stderr, "Warning, i915 perf is in paranoid mode\n" "You might want to run :\n" "\tsudo sysctl dev.i915.perf_stream_paranoid=0\n"); } assert(drm_card >= 0); snprintf(buffer, sizeof(buffer), "/sys/class/drm/card%d/metrics", drm_card); metrics_dir = opendir(buffer); if (metrics_dir == NULL) return false; while ((entry = readdir(metrics_dir))) { struct gputop_metric_set *metric_set; struct hash_entry *metrics_entry; if (entry->d_type != DT_DIR || entry->d_name[0] == '.') continue; metrics_entry = _mesa_hash_table_search(gen_metrics->metric_sets_map, entry->d_name); if (metrics_entry == NULL) continue; metric_set = (struct gputop_metric_set*)metrics_entry->data; snprintf(buffer, sizeof(buffer), "metrics/%s/id", metric_set->hw_config_guid); if (sysfs_card_read(buffer, &metric_set->perf_oa_metrics_set)) { array_append(gputop_perf_oa_supported_metric_set_uuids, &metric_set->hw_config_guid); } } closedir(metrics_dir); return true; } // function that hard-codes the guids specific for the broadwell configuration bool gputop_enumerate_metrics_fake(void) { static const char *fake_bdw_guids[] = { "b541bd57-0e0f-4154-b4c0-5858010a2bf7", "35fbc9b2-a891-40a6-a38d-022bb7057552", "233d0544-fff7-4281-8291-e02f222aff72", "2b255d48-2117-4fef-a8f7-f151e1d25a2c", "f7fd3220-b466-4a4d-9f98-b0caf3f2394c", "e99ccaca-821c-4df9-97a7-96bdb7204e43", "27a364dc-8225-4ecb-b607-d6f1925598d9", "857fc630-2f09-4804-85f1-084adfadd5ab", "343ebc99-4a55-414c-8c17-d8e259cf5e20", "78490af2-10fa-430b-ae3c-94ec04d5214e", "c0abdd97-3b13-4cad-814c-bd178804e02c", "ad665281-a7cf-483a-bd10-0e07c43f61c7", "930a15aa-4300-4fce-a9ba-edb0b9e880be", "d7793b26-b5e3-4f0f-ad78-7ebc9d0b4c7d", "da0f7875-1143-4d73-a39c-9128a951c46a", "52c186e4-39e3-4534-87cd-41bd47763df9", "edcb8c31-764d-451a-9ecd-c9c89fb54f8d", "729fc3f4-ccff-4902-be6b-f1a22cc92c02", "29598975-4785-43ab-a981-1dfa58d0e835", "8fb61ba2-2fbb-454c-a136-2dec5a8a595e", "e1743ca0-7fc8-410b-a066-de7bbb9280b7", "0a9eb7be-feee-4275-a139-6d9cedf0fdb0", "d6de6f55-e526-4f79-a6a6-d7315c09044e", "e713f347-953e-4d8c-b02f-6be31df2db2b", }; struct gputop_metric_set *metric_set; struct hash_entry *metrics_entry; int i; for (i = 0; i < ARRAY_SIZE(fake_bdw_guids); i++){ metrics_entry = _mesa_hash_table_search(gen_metrics->metric_sets_map, fake_bdw_guids[i]); metric_set = (struct gputop_metric_set*)metrics_entry->data; metric_set->perf_oa_metrics_set = i; array_append(gputop_perf_oa_supported_metric_set_uuids, &metric_set->hw_config_guid); } return true; } bool gputop_perf_initialize(void) { struct gen_device_info devinfo; list_inithead(&ctx_handles_list); if (gputop_devinfo.topology.max_slices) return true; if (getenv("GPUTOP_FAKE_MODE") && strcmp(getenv("GPUTOP_FAKE_MODE"), "1") == 0) { gputop_fake_mode = true; intel_dev.device = 5654; // broadwell specific id } else { drm_fd = open_render_node(&intel_dev); if (drm_fd < 0) { gputop_log(GPUTOP_LOG_LEVEL_HIGH, "Failed to open render node", -1); return false; } drm_card = get_card_for_fd(drm_fd); } if (getenv("GPUTOP_DISABLE_OACONFIG") && strcmp(getenv("GPUTOP_DISABLE_OACONFIG"), "1") == 0) gputop_disable_oaconfig = true; /* NB: eu_count needs to be initialized before declaring counters */ page_size = sysconf(_SC_PAGE_SIZE); gen_metrics = NULL; gputop_perf_oa_supported_metric_set_uuids = array_new(sizeof(char*), 1); if (!gen_get_device_info_from_pci_id(intel_dev.device, &devinfo)) { gputop_log(GPUTOP_LOG_LEVEL_HIGH, "Failed to recognize device id\n", -1); return false; } if (init_dev_info(drm_fd, intel_dev.device, &devinfo)) { if (gputop_fake_mode) return gputop_enumerate_metrics_fake(); else { gputop_reload_userspace_metrics(drm_fd); return gputop_enumerate_metrics_via_sysfs(); } } else return false; } void gputop_perf_free(void) { ralloc_free(gen_metrics); gen_metrics = NULL; array_free(gputop_perf_oa_supported_metric_set_uuids); } const struct gputop_devinfo * gputop_perf_get_devinfo(void) { return &gputop_devinfo; } ================================================ FILE: server/gputop-perf.h ================================================ /* * GPU Top * * Copyright (C) 2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include #include #include #include "util/list.h" #include "gputop-oa-metrics.h" uint64_t get_time(void); struct ctx_handle { struct list_head link; uint32_t id; int fd; }; /* * This structure tracks the offsets to the perf record headers in our * perf circular buffer so that we can enable perf's flight recorder * mode whereby perf may overwrite old samples and records with new * ones but in doing so it trashes the perf headers that we need to * determine the location of sequential records. * * The alternative to this would be to copy all data out of the perf * circular buffer into another buffer, so it can't be overwritten by * perf but that would demand further memory bandwidth that we want to * avoid wasting. * * With this approach we don't *actually* enable perf's flight * recorder mode, because as we update our record of header offsets we * can update the perf tail to say that these records have been read * so we can have our flight recorder mode without perf knowing. The * advantage of this is that if for some corner case userspace gets * blocked from updating its record of header offsets for a long time * and the kernel comes to wrap around then we will get notified of * that condition by the kernel. In that case we end up loosing recent * samples instead of old ones, but something has to have gone quite * badly wrong in that case anyway so it's hopefully better to report * errors reliably instead. * * To simplify this, there is a limit on the number of headers we * track, based on the expected number of samples that could fit * in a full perf circular buffer. * * The header offsets are stored in a circular buffer of packed uint32 * values. * * Due to the fixed size of this buffer, but the possibility of many * small perf records, (much smaller than our expected samples), * there's a small chance that we fill this buffer and still loose * track of some older headers. We can report this case as an error * though, and this is a more graceful failure than having to scrap * the entire perf buffer. * * * For each update of this buffer we: * * 1) Check what new records have been added: * * * if buf->last_perf_head uninitialized, set it to the perf tail * * foreach new record from buf->last_perf_head to the current perf head: * - check there's room for a new header offset, but if not: * - report an error * - move the tail forward (loosing a record) * - add a header offset to buf->offsets[buf->head] * - buf->head = (buf->head + 1) % buf->len; * - recognise when the perf head wraps and mark the buffer 'full' * * 2) Optionally parse any of the new records (i.e. before we update * tail) * * Typically we aren't processing the records while tracing, but * beware that if anything does need passing on the fly then it * needs to be done before we update the tail pointer below. * * 3) If buf 'full'; check how much of perf's tail has been eaten: * * * move buf->tail forward to the next offset that is ahead of * perf's (head + header->size) * XXX: we can assert() that we don't overtake buf->head. That * shouldn't be possible if we aren't enabling perf's * overwriting/flight recorder mode. * XXX: Note: we do this after checking for new records so we * don't have to worry about the corner case of eating more * than we previously knew about. * * 4) Set perf's tail to perf's head (i.e. consume everything so that * perf won't block when wrapping around and overwriting old * samples.) * * XXX: Note: if tracing and using this structure to track headers * then when you want to process all the collected data, it's * necessary to stop/disable the event before consuming data from the * perf circular buffer due to how we manage the tail pointer (there's * nothing stopping perf from overwriting all the current data) */ struct gputop_perf_header_buf { uint32_t *offsets; uint32_t len; uint32_t head; uint32_t tail; uint32_t last_perf_head; bool full; /* Set when we first wrap. */ }; enum gputop_perf_stream_type { GPUTOP_STREAM_PERF, GPUTOP_STREAM_I915_PERF, GPUTOP_STREAM_CPU, }; struct gputop_perf_stream { int ref_count; struct gputop_metric_set *metric_set; bool overwrite; enum gputop_perf_stream_type type; union { /* i915 perf event */ struct { int buf_sizes; uint8_t *bufs[2]; uint8_t *last; int last_buf_idx; bool header_written; uint32_t total_len; } oa; /* linux perf event */ struct { /* The mmaped circular buffer for collecting samples from perf */ struct perf_event_mmap_page *mmap_page; uint8_t *buffer; size_t buffer_size; struct gputop_perf_header_buf header_buf; bool header_written; uint32_t total_len; uint64_t head; uint64_t tail; } perf; /* /proc/stat */ struct { uv_timer_t sample_timer; struct cpu_stat *stats_buf; int stats_buf_len; /* N cpu_stat structures (multiple of n_cpus) */ int stats_buf_pos; bool stats_buf_full; } cpu; }; int fd; uv_poll_t fd_poll; uv_timer_t fd_timer; void (*ready_cb)(struct gputop_perf_stream *); bool live_updates; int n_closing_uv_handles; void (*on_close_cb)(struct gputop_perf_stream *stream); bool pending_close; bool closed; bool per_ctx_mode; // fields used for fake data: uint64_t start_time; // stream opening time uint32_t gen_so_far; // amount of reports generated since stream opening uint32_t prev_clocks; // the previous value of clock ticks uint32_t period; // the period in nanoseconds calculated from exponent uint32_t prev_timestamp; // the previous timestamp value /* XXX: reserved for whoever opens the stream */ struct { uint32_t id; struct list_head link; void *data; void (*destroy_cb)(struct gputop_perf_stream *stream); bool flushing; } user; }; /* E.g. for tracing vs rolling view */ struct perf_oa_user { void (*sample)(struct gputop_perf_stream *stream, uint8_t *start, uint8_t *end); }; bool gputop_add_ctx_handle(int ctx_fd, uint32_t ctx_id); bool gputop_remove_ctx_handle(uint32_t ctx_id); struct ctx_handle *get_first_available_ctx(char **error); bool gputop_perf_initialize(void); void gputop_perf_free(void); extern struct gputop_gen *gen_metrics; extern struct array *gputop_perf_oa_supported_metric_set_uuids; extern int gputop_perf_trace_buffer_size; extern uint8_t *gputop_perf_trace_buffer; extern bool gputop_perf_trace_empty; extern bool gputop_perf_trace_full; extern uint8_t *gputop_perf_trace_head; extern int gputop_perf_n_samples; extern bool gputop_fake_mode; struct gputop_perf_stream * gputop_open_i915_perf_oa_stream(struct gputop_metric_set *metric_set, int period_exponent, struct ctx_handle *ctx, bool cpu_timestamps, bool gpu_timestamps, void (*ready_cb)(struct gputop_perf_stream *), bool overwrite, char **error); struct gputop_perf_stream * gputop_perf_open_tracepoint(int pid, int cpu, uint64_t id, size_t trace_struct_size, size_t perf_buffer_size, void (*ready_cb)(struct gputop_perf_stream *), bool overwrite, char **error); struct gputop_perf_stream * gputop_perf_open_generic_counter(int pid, int cpu, uint64_t type, uint64_t config, size_t perf_buffer_size, void (*ready_cb)(uv_poll_t *poll, int status, int events), bool overwrite, char **error); struct gputop_perf_stream * gputop_perf_open_cpu_stats(bool overwrite, uint64_t sample_period_ms); bool gputop_stream_data_pending(struct gputop_perf_stream *stream); void gputop_perf_update_header_offsets(struct gputop_perf_stream *stream); int gputop_perf_fake_read(struct gputop_perf_stream *stream, uint8_t *buf, int buf_length); void gputop_perf_read_samples(struct gputop_perf_stream *stream); void gputop_i915_perf_print_records(struct gputop_perf_stream *stream, uint8_t *buf, int len); void gputop_perf_stream_close(struct gputop_perf_stream *stream, void (*on_close_cb)(struct gputop_perf_stream *stream)); void gputop_perf_stream_ref(struct gputop_perf_stream *stream); void gputop_perf_stream_unref(struct gputop_perf_stream *stream); const struct gputop_devinfo *gputop_perf_get_devinfo(void); bool gputop_perf_kernel_has_i915_oa_cpu_timestamps(void); bool gputop_perf_kernel_has_i915_oa_gpu_timestamps(void); ================================================ FILE: server/gputop-server.c ================================================ /* * GPU Top * * Copyright (C) 2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "gputop-server.h" #include "gputop-perf.h" #include "gputop-util.h" #include "gputop-sysutil.h" #include "gputop-cpu.h" #include "gputop-mainloop.h" #include "gputop-log.h" #include "gputop.pb-c.h" #include "gputop-debugfs.h" #include "dev/gen_device_info.h" #include "util/list.h" #include "util/macros.h" #ifdef SUPPORT_GL #include "gputop-gl.h" #endif static h2o_websocket_conn_t *h2o_conn; static h2o_globalconf_t config; static h2o_context_t ctx; static SSL_CTX *ssl_ctx; static uv_tcp_t listener; static uv_timer_t timer; static bool update_queued; static uv_idle_t update_idle; enum { WS_MESSAGE_PERF = 1, WS_MESSAGE_PROTOBUF, WS_MESSAGE_I915_PERF, }; static struct list_head streams; static struct list_head closing_streams; static void send_pb_message(h2o_websocket_conn_t *conn, ProtobufCMessage *pb_message) { struct wslay_event_msg msg; uint8_t *data; if (!conn) return; msg.opcode = WSLAY_BINARY_FRAME; msg.msg_length = 8 + protobuf_c_message_get_packed_size(pb_message); data = xmalloc(msg.msg_length); data[0] = WS_MESSAGE_PROTOBUF; protobuf_c_message_pack(pb_message, &data[8]); msg.msg = data; wslay_event_queue_msg(conn->ws_ctx, &msg); wslay_event_send(conn->ws_ctx); free(data); } static void stream_closed_cb(struct gputop_perf_stream *stream) { list_del(&stream->user.link); gputop_perf_stream_unref(stream); } static void stream_closed_notify_cb(struct gputop_perf_stream *stream) { Gputop__Message message_ack = GPUTOP__MESSAGE__INIT; Gputop__Message message = GPUTOP__MESSAGE__INIT; Gputop__CloseNotify notify = GPUTOP__CLOSE_NOTIFY__INIT; /* stream->user.data will = a UUID if it was closed * in response to a remote request which we need to * ACK... */ if (stream->user.data) { message_ack.reply_uuid = stream->user.data; message_ack.cmd_case = GPUTOP__MESSAGE__CMD_ACK; message_ack.ack = true; dbg("CMD_ACK: %s\n", (char *)stream->user.data); send_pb_message(h2o_conn, &message_ack.base); free(stream->user.data); stream->user.data = NULL; } notify.id = stream->user.id; message.cmd_case = GPUTOP__MESSAGE__CMD_CLOSE_NOTIFY; message.close_notify = ¬ify; send_pb_message(h2o_conn, &message.base); stream_closed_cb(stream); } /* * FIXME: don't duplicate these... */ #define TAKEN(HEAD, TAIL, POT_SIZE) (((HEAD) - (TAIL)) & (POT_SIZE - 1)) /* Note: this will equate to 0 when the buffer is exactly full... */ #define REMAINING(HEAD, TAIL, POT_SIZE) (POT_SIZE - TAKEN (HEAD, TAIL, POT_SIZE)) #if defined(__i386__) #define rmb() __asm__ volatile("lock; addl $0,0(%%esp)" ::: "memory") #define mb() __asm__ volatile("lock; addl $0,0(%%esp)" ::: "memory") #endif #if defined(__x86_64__) #define rmb() __asm__ volatile("lfence" ::: "memory") #define mb() __asm__ volatile("mfence" ::: "memory") #endif struct perf_flush_closure { bool header_written; int id; int total_len; struct gputop_perf_stream *stream; uint64_t head; uint64_t tail; }; static unsigned int read_perf_head(struct perf_event_mmap_page *mmap_page) { unsigned int head = (*(volatile uint64_t *)&mmap_page->data_head); rmb(); return head; } static void write_perf_tail(struct perf_event_mmap_page *mmap_page, unsigned int tail) { /* Make sure we've finished reading all the sample data we * were consuming before updating the tail... */ mb(); mmap_page->data_tail = tail; } static ssize_t fragmented_perf_read_cb(wslay_event_context_ptr ctx, uint8_t *data, size_t len, const union wslay_event_msg_source *_source, int *eof, void *user_data) { union wslay_event_msg_source *source = (union wslay_event_msg_source *) _source; struct gputop_perf_stream *stream = source->data; uint64_t mask; int read_len; int total = 0; uint64_t head; uint64_t tail; uint64_t remainder; uint8_t *buffer; uint8_t *p; if (!stream) { *eof = 1; return 0; } mask = stream->perf.buffer_size - 1; if (!stream->perf.header_written) { assert(len > 8); memset(data, 0, 8); data[0] = WS_MESSAGE_PERF; *(uint32_t *)(data + 4) = stream->user.id; total = 8; data += 8; len -= 8; stream->perf.header_written = true; } head = stream->perf.head; tail = stream->perf.tail; buffer = stream->perf.buffer; if ((head & mask) < (tail & mask)) { int before; p = buffer + (tail & mask); before = stream->perf.buffer_size - (tail & mask); read_len = MIN(before, len); memcpy(data, p, read_len); len -= read_len; tail += read_len; data += read_len; total += read_len; stream->perf.tail = tail; } p = buffer + (tail & mask); remainder = TAKEN(head, tail, stream->perf.buffer_size); read_len = MIN(remainder, len); memcpy(data, p, read_len); len -= read_len; tail += read_len; total += read_len; stream->perf.tail = tail; stream->perf.total_len += total; if (TAKEN(head, tail, stream->perf.buffer_size) == 0) { *eof = 1; write_perf_tail(stream->perf.mmap_page, tail); stream->user.flushing = false; if (stream->pending_close) gputop_perf_stream_close(stream, stream_closed_notify_cb); source->data = NULL; } return total; } static void flush_perf_stream_samples(struct gputop_perf_stream *stream) { uint64_t head = read_perf_head(stream->perf.mmap_page); uint64_t tail = stream->perf.mmap_page->data_tail; struct wslay_event_fragmented_msg msg; if (stream->user.flushing) return; stream->user.flushing = true; //gputop_perf_print_records(stream, head, tail, false); stream->perf.header_written = false; stream->perf.total_len = 0; stream->perf.head = head; stream->perf.tail = tail; memset(&msg, 0, sizeof(msg)); msg.opcode = WSLAY_BINARY_FRAME; msg.source.data = stream; msg.read_callback = fragmented_perf_read_cb; wslay_event_queue_fragmented_msg(h2o_conn->ws_ctx, &msg); wslay_event_send(h2o_conn->ws_ctx); } static ssize_t fragmented_i915_perf_read_cb(wslay_event_context_ptr ctx, uint8_t *data, size_t len, const union wslay_event_msg_source *_source, int *eof, void *user_data) { union wslay_event_msg_source *source = (union wslay_event_msg_source *) _source; struct gputop_perf_stream *stream = source->data; int total = 0; int read_len; if (!stream) { *eof = 1; return 0; } if (!stream->oa.header_written) { assert(len > 8); memset(data, 0, 8); data[0] = WS_MESSAGE_I915_PERF; *(uint32_t *)(data + 4) = stream->user.id; total = 8; data += 8; len -= 8; stream->oa.header_written = true; } if (gputop_fake_mode) read_len = gputop_perf_fake_read(stream, data, len); else while ((read_len = read(stream->fd, data, len)) < 0 && errno == EINTR) ; if (read_len > 0) { total += read_len; stream->oa.total_len += total; } else { *eof = 1; if (!gputop_fake_mode && errno != EAGAIN) dbg("Error reading i915 perf stream %m\n"); stream->user.flushing = false; if (stream->pending_close) gputop_perf_stream_close(stream, stream_closed_notify_cb); source->data = NULL; } return total; } static void flush_i915_perf_stream_samples(struct gputop_perf_stream *stream) { struct wslay_event_fragmented_msg msg; if (stream->user.flushing) return; //gputop_perf_print_records(stream, head, tail, false); stream->user.flushing = true; stream->oa.header_written = false; stream->oa.total_len = 0; memset(&msg, 0, sizeof(msg)); msg.opcode = WSLAY_BINARY_FRAME; msg.source.data = stream; msg.read_callback = fragmented_i915_perf_read_cb; wslay_event_queue_fragmented_msg(h2o_conn->ws_ctx, &msg); wslay_event_send(h2o_conn->ws_ctx); } static void flush_cpu_stats(struct gputop_perf_stream *stream) { int n_cpus = gputop_cpu_count(); int n; int pos; if (stream->cpu.stats_buf_pos == 0 && !stream->cpu.stats_buf_full) return; if (stream->cpu.stats_buf_full) { n = stream->cpu.stats_buf_len / n_cpus; pos = stream->cpu.stats_buf_pos; } else { n = stream->cpu.stats_buf_pos / n_cpus; pos = 0; } for (int i = 0; i < n; i++) { Gputop__Message message = GPUTOP__MESSAGE__INIT; Gputop__CpuStatsSet set = GPUTOP__CPU_STATS_SET__INIT; Gputop__CpuStats **stats_vec; Gputop__CpuStats *stats; struct cpu_stat *stat = stream->cpu.stats_buf + pos; stats_vec = alloca(sizeof(void *) * n_cpus); stats = alloca(sizeof(Gputop__CpuStats) * n_cpus); message.cmd_case = GPUTOP__MESSAGE__CMD_CPU_STATS; message.cpu_stats = &set; set.id = stream->user.id; set.n_cpus = n_cpus; set.cpus = stats_vec; for (int i = 0; i < n_cpus; i++) { gputop__cpu_stats__init(&stats[i]); stats_vec[i] = &stats[i]; stats[i].timestamp = stat[i].timestamp; stats[i].user = stat[i].user; stats[i].nice = stat[i].nice; stats[i].system = stat[i].system; stats[i].idle = stat[i].idle; stats[i].iowait = stat[i].iowait; stats[i].irq = stat[i].irq; stats[i].softirq = stat[i].softirq; stats[i].steal = stat[i].steal; stats[i].guest = stat[i].guest; stats[i].guest_nice = stat[i].guest_nice; } send_pb_message(h2o_conn, &message.base); pos += n_cpus; if (pos >= stream->cpu.stats_buf_len) pos = 0; } stream->cpu.stats_buf_pos = 0; stream->cpu.stats_buf_full = false; } static void flush_stream_samples(struct gputop_perf_stream *stream) { if (stream->user.flushing) { fprintf(stderr, "Throttling websocket forwarding\n"); return; } assert(!stream->pending_close); assert(!stream->closed); if (!gputop_stream_data_pending(stream)) return; switch (stream->type) { case GPUTOP_STREAM_PERF: flush_perf_stream_samples(stream); break; case GPUTOP_STREAM_I915_PERF: flush_i915_perf_stream_samples(stream); break; case GPUTOP_STREAM_CPU: flush_cpu_stats(stream); break; } } static void update_perf_head_pointers(struct gputop_perf_stream *stream) { struct gputop_perf_header_buf *hdr_buf = &stream->perf.header_buf; gputop_perf_update_header_offsets(stream); if (!hdr_buf->full) { Gputop__Message message = GPUTOP__MESSAGE__INIT; Gputop__BufferFillNotify notify = GPUTOP__BUFFER_FILL_NOTIFY__INIT; notify.stream_id = stream->user.id; notify.fill_percentage = (hdr_buf->offsets[(hdr_buf->head - 1) % hdr_buf->len] / (float)stream->perf.buffer_size) * 100.0f; message.cmd_case = GPUTOP__MESSAGE__CMD_FILL_NOTIFY; message.fill_notify = ¬ify; send_pb_message(h2o_conn, &message.base); } } static void update_streams(void) { list_for_each_entry_safe(struct gputop_perf_stream, stream, &streams, user.link) { if (stream->live_updates) flush_stream_samples(stream); else if (stream->type == GPUTOP_STREAM_PERF) update_perf_head_pointers(stream); } } static void forward_logs(void) { Gputop__Log *log = gputop_get_pb_log(); if (log) { Gputop__Message msg = GPUTOP__MESSAGE__INIT; server_dbg("forwarding log to UI\n"); msg.cmd_case = GPUTOP__MESSAGE__CMD_LOG; msg.log = log; send_pb_message(h2o_conn, &msg.base); gputop_pb_log_free(log); } } static void update_cb(uv_idle_t *idle) { uv_idle_stop(&update_idle); update_queued = false; update_streams(); forward_logs(); } /* We may have a number of metric streams with events for available data being * delievered via the libuv mainloop but to minimize the time spent responding * and forwarding those metrics to any UI we consolidate the follow up work via * an idle mainloop callback... */ static void queue_update(void) { if (update_queued) return; uv_idle_start(&update_idle, update_cb); } static void periodic_update_cb(uv_timer_t *timer) { queue_update(); } static void i915_perf_ready_cb(struct gputop_perf_stream *stream) { queue_update(); } static void handle_open_i915_perf_oa_stream(h2o_websocket_conn_t *conn, Gputop__Request *request) { Gputop__OpenStream *open_stream = request->open_stream; uint32_t id = open_stream->id; Gputop__OAStreamInfo *oa_stream_info = open_stream->oa_stream; struct gputop_metric_set *metric_set = NULL; struct hash_entry *entry = NULL; struct gputop_perf_stream *stream; char *error = NULL; struct ctx_handle *ctx = NULL; Gputop__Message message = GPUTOP__MESSAGE__INIT; message.reply_uuid = request->uuid; message.ack = true; if (!gputop_perf_initialize()) { int ret = asprintf(&error, "Failed to initialize perf\n"); (void) ret; goto err; } dbg("handle_open_i915_perf_oa_stream: id = %d\n", id); entry = _mesa_hash_table_search(gen_metrics->metric_sets_map, oa_stream_info->uuid); if (entry != NULL) { metric_set = entry->data; } else { int ret = asprintf(&error, "uuid is not available\n"); (void) ret; goto err; } // TODO: (matt-auld) // Currently we don't support selectable contexts, so we just use the // first one which is available to us. Though this would only really // make sense if we could make the list of contexts visible to the user. // Maybe later the per_ctx_mode could become the context handle... if (oa_stream_info->per_ctx_mode) { ctx = get_first_available_ctx(&error); if (!ctx) goto err; } stream = gputop_open_i915_perf_oa_stream(metric_set, oa_stream_info->period_exponent, ctx, oa_stream_info->cpu_timestamps, oa_stream_info->gpu_timestamps, (open_stream->live_updates ? i915_perf_ready_cb : NULL), open_stream->overwrite, &error); if (stream) { stream->user.id = id; list_addtail(&stream->user.link, &streams); stream->live_updates = open_stream->live_updates; } else { dbg("Failed to open perf stream set=%s period=%d: %s\n", oa_stream_info->uuid, oa_stream_info->period_exponent, error); goto err; } message.reply_uuid = request->uuid; message.cmd_case = GPUTOP__MESSAGE__CMD_ACK; message.ack = true; send_pb_message(conn, &message.base); return; err: message.cmd_case = GPUTOP__MESSAGE__CMD_ERROR; message.error = error; send_pb_message(conn, &message.base); free(error); return; } static void handle_open_tracepoint(h2o_websocket_conn_t *conn, Gputop__Request *request) { Gputop__OpenStream *open_stream = request->open_stream; uint32_t id = open_stream->id; Gputop__TracepointConfig *config = open_stream->tracepoint; struct gputop_perf_stream *stream; char *error = NULL; int buffer_size; Gputop__Message message = GPUTOP__MESSAGE__INIT; if (!gputop_perf_initialize()) { message.reply_uuid = request->uuid; message.cmd_case = GPUTOP__MESSAGE__CMD_ERROR; message.error = "Failed to initialize perf\n"; send_pb_message(conn, &message.base); return; } /* NB: Perf buffer size must be a power of two. * We don't need a large buffer if we're periodically forwarding data */ if (open_stream->live_updates) buffer_size = 128 * 1024; else buffer_size = 16 * 1024 * 1024; stream = gputop_perf_open_tracepoint(config->pid, config->cpu, config->id, 12, /* FIXME: guess trace struct size * used to estimate number of samples * that will fit in buffer */ buffer_size, NULL, open_stream->overwrite, &error); if (stream) { stream->user.id = id; list_addtail(&stream->user.link, &streams); stream->live_updates = open_stream->live_updates; } else { dbg("Failed to open trace %"PRIu32": %s\n", config->id, error); free(error); } message.reply_uuid = request->uuid; message.cmd_case = GPUTOP__MESSAGE__CMD_ACK; message.ack = true; send_pb_message(conn, &message.base); } static void handle_open_generic_stream(h2o_websocket_conn_t *conn, Gputop__Request *request) { Gputop__OpenStream *open_stream = request->open_stream; uint32_t id = open_stream->id; Gputop__GenericEventInfo *generic_info = open_stream->generic; struct gputop_perf_stream *stream; char *error = NULL; int buffer_size; Gputop__Message message = GPUTOP__MESSAGE__INIT; if (!gputop_perf_initialize()) { message.reply_uuid = request->uuid; message.cmd_case = GPUTOP__MESSAGE__CMD_ERROR; message.error = "Failed to initialize perf\n"; send_pb_message(conn, &message.base); return; } /* NB: Perf buffer size must be a power of two. * We don't need a large buffer if we're periodically forwarding data */ if (open_stream->live_updates) buffer_size = 128 * 1024; else buffer_size = 16 * 1024 * 1024; stream = gputop_perf_open_generic_counter(generic_info->pid, generic_info->cpu, generic_info->type, generic_info->config, buffer_size, NULL, open_stream->overwrite, &error); if (stream) { stream->user.id = id; list_inithead(&stream->user.link); list_addtail(&stream->user.link, &streams); stream->live_updates = open_stream->live_updates; } else { dbg("Failed to open perf event: %s\n", error); free(error); } message.reply_uuid = request->uuid; message.cmd_case = GPUTOP__MESSAGE__CMD_ACK; message.ack = true; send_pb_message(conn, &message.base); } static void handle_open_cpu_stats(h2o_websocket_conn_t *conn, Gputop__Request *request) { Gputop__OpenStream *open_stream = request->open_stream; uint32_t id = open_stream->id; Gputop__CpuStatsInfo *stats_info = open_stream->cpu_stats; Gputop__Message message = GPUTOP__MESSAGE__INIT; struct gputop_perf_stream *stream; if (!gputop_perf_initialize()) { message.reply_uuid = request->uuid; message.cmd_case = GPUTOP__MESSAGE__CMD_ERROR; message.error = "Failed to initialize perf\n"; send_pb_message(conn, &message.base); return; } stream = gputop_perf_open_cpu_stats(open_stream->overwrite, stats_info->sample_period_ms); if (stream) { stream->user.id = id; list_inithead(&stream->user.link); list_addtail(&stream->user.link, &streams); stream->live_updates = open_stream->live_updates; } message.reply_uuid = request->uuid; message.cmd_case = GPUTOP__MESSAGE__CMD_ACK; message.ack = true; send_pb_message(conn, &message.base); } static void handle_open_stream(h2o_websocket_conn_t *conn, Gputop__Request *request) { Gputop__OpenStream *open_stream = request->open_stream; Gputop__Message message = GPUTOP__MESSAGE__INIT; switch (open_stream->type_case) { case GPUTOP__OPEN_STREAM__TYPE_OA_STREAM: handle_open_i915_perf_oa_stream(conn, request); break; case GPUTOP__OPEN_STREAM__TYPE_TRACEPOINT: handle_open_tracepoint(conn, request); break; case GPUTOP__OPEN_STREAM__TYPE_GENERIC: handle_open_generic_stream(conn, request); break; case GPUTOP__OPEN_STREAM__TYPE_CPU_STATS: handle_open_cpu_stats(conn, request); break; default: message.reply_uuid = request->uuid; message.cmd_case = GPUTOP__MESSAGE__CMD_ERROR; message.error = "FIXME: implement support for opening GL queries\n"; send_pb_message(conn, &message.base); fprintf(stderr, "TODO: support opening GL queries"); } } static void close_stream(struct gputop_perf_stream *stream) { /* By moving the stream into the closing_streams list we ensure we * won't forward anymore for the stream in case we can't close the * stream immediately. */ list_del(&stream->user.link); list_addtail(&stream->user.link, &closing_streams); stream->pending_close = true; /* NB: we can't synchronously close the perf event if we're in the * middle of writing samples to the websocket... */ if (!stream->user.flushing) gputop_perf_stream_close(stream, stream_closed_notify_cb); } static void terminate_all_streams(void) { list_for_each_entry_safe(struct gputop_perf_stream, stream, &streams, user.link) { gputop_perf_stream_close(stream, stream_closed_cb); } list_for_each_entry_safe(struct gputop_perf_stream, stream, &closing_streams, user.link) { gputop_perf_stream_close(stream, stream_closed_cb); } } static void handle_close_stream(h2o_websocket_conn_t *conn, Gputop__Request *request) { uint32_t id = request->close_stream; dbg("handle_close_stream: id=%d, request_uuid=%s\n", id, request->uuid); list_for_each_entry_safe(struct gputop_perf_stream, stream, &streams, user.link) { if (stream->user.id == id) { assert(stream->user.data == NULL); stream->user.data = strdup(request->uuid); close_stream(stream); return; } } } static bool gputop_get_pid_prop(uint32_t pid, const char *prop, char *buf, int len) { FILE *fp; char *line = NULL; size_t line_len = 0; ssize_t nread; char pid_path[512]; bool res = false; memset(buf, 0, len); snprintf(buf, len, "Unknown"); snprintf(pid_path, sizeof(pid_path), "/proc/%d/%s", pid, prop); fp = fopen(pid_path, "r"); if (!fp) return false; nread = getline(&line, &line_len, fp); if (nread != -1) { int i; for (i = 0; i < nread; i++) { if (line[i] == '\n') { line[i] = '\0'; break; } } snprintf(buf, len, "%s", line); res = true; } fclose(fp); free(line); return res; } static void handle_get_process_info(h2o_websocket_conn_t *conn, Gputop__Request *request) { char cmdline[256]; char comm[256]; char error[80]; uint32_t pid = request->get_process_info; bool cmdline_good, comm_good; Gputop__Message message = GPUTOP__MESSAGE__INIT; Gputop__ProcessInfo process_info = GPUTOP__PROCESS_INFO__INIT; message.reply_uuid = request->uuid; cmdline_good = gputop_get_pid_prop(pid, "cmdline", cmdline, sizeof(cmdline)); comm_good = gputop_get_pid_prop(pid, "comm", comm, sizeof(comm)); if (cmdline_good || comm_good) { dbg(" Sending PID = %d\n", pid); message.cmd_case = GPUTOP__MESSAGE__CMD_PROCESS_INFO; process_info.pid = pid; process_info.cmd_line = cmdline; process_info.comm = comm; message.process_info = &process_info; send_pb_message(conn, &message.base); return; } snprintf(error, sizeof(error), "Failed to find process %d", pid); message.cmd_case = GPUTOP__MESSAGE__CMD_ERROR; message.error = error; send_pb_message(conn, &message.base); dbg("Failed to find process %d\n", pid); } static void handle_get_tracepoint_info(h2o_websocket_conn_t *conn, Gputop__Request *request) { char *name = request->get_tracepoint_info; char filename[1024]; int len = 0; Gputop__Message message = GPUTOP__MESSAGE__INIT; Gputop__TracepointInfo tracepoint_info = GPUTOP__TRACEPOINT_INFO__INIT; message.reply_uuid = request->uuid; snprintf(filename, sizeof(filename), "tracing/events/%s/format", name); tracepoint_info.sample_format = gputop_debugfs_read(filename, &len); if (!tracepoint_info.sample_format) goto error; snprintf(filename, sizeof(filename), "tracing/events/%s/id", name); tracepoint_info.event_id = gputop_debugfs_read_uint64(filename); message.cmd_case = GPUTOP__MESSAGE__CMD_TRACEPOINT_INFO; message.tracepoint_info = &tracepoint_info; send_pb_message(conn, &message.base); free(tracepoint_info.sample_format); return; error: message.cmd_case = GPUTOP__MESSAGE__CMD_ERROR; send_pb_message(conn, &message.base); } #ifdef SUPPORT_GL static Gputop__GLQueryInfo ** get_gl_query_info(int *n_queries_ret) { Gputop__GLQueryInfo **queries_vec = NULL; Gputop__GLQueryInfo *queries = NULL; int n_queries = 0; pthread_rwlock_rdlock(&gputop_gl_lock); /* XXX: we currently assume if there are multiple contexts in use, they * have the same queries, with the same IDs available... */ if (gputop_gl_contexts->len) { struct winsys_context **contexts = gputop_gl_contexts->data; struct winsys_context *first_wctx = contexts[0]; int i; n_queries = list_length(&first_wctx->queries); queries_vec = xmalloc(sizeof(void *) * n_queries); queries = xmalloc(sizeof(Gputop__GLQueryInfo) * n_queries); i = 0; list_for_each_entry(struct intel_query_info, q, &first_wctx->queries, link) { Gputop__GLQueryInfo *query = &queries[i]; Gputop__GLCounter **counters_vec; Gputop__GLCounter *counters; query->name = q->name; query->id = q->id; counters_vec = xmalloc(sizeof(void *) * q->n_counters); counters = xmalloc(sizeof(Gputop__GLCounter) * q->n_counters); query->n_counters = q->n_counters; query->counters = counters_vec; for (int j = 0; j < query->n_counters; j++) { struct intel_counter *c = &q->counters[j]; Gputop__GLCounter *counter = &counters[j]; counter->id = c->id; counter->name = c->name; counter->description = c->description; counter->maximum = c->max_raw_value; switch (c->type) { case GL_PERFQUERY_COUNTER_EVENT_INTEL: counter->type = GPUTOP__GLCOUNTER_TYPE__EVENT; break; case GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL: counter->type = GPUTOP__GLCOUNTER_TYPE__DURATION_NORM; break; case GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL: counter->type = GPUTOP__GLCOUNTER_TYPE__DURATION_RAW; break; case GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL: counter->type = GPUTOP__GLCOUNTER_TYPE__THROUGHPUT; break; case GL_PERFQUERY_COUNTER_RAW_INTEL: counter->type = GPUTOP__GLCOUNTER_TYPE__RAW; break; case GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL: counter->type = GPUTOP__GLCOUNTER_TYPE__TIMESTAMP; break; } switch(c->data_type) { case GPUTOP_PERFQUERY_COUNTER_DATA_UINT32: counter->data_type = GPUTOP__GLCOUNTER_DATA_TYPE__UINT32; break; case GPUTOP_PERFQUERY_COUNTER_DATA_UINT64: counter->data_type = GPUTOP__GLCOUNTER_DATA_TYPE__UINT64; break; case GPUTOP_PERFQUERY_COUNTER_DATA_FLOAT: counter->data_type = GPUTOP__GLCOUNTER_DATA_TYPE__FLOAT; break; case GPUTOP_PERFQUERY_COUNTER_DATA_DOUBLE: counter->data_type = GPUTOP__GLCOUNTER_DATA_TYPE__DOUBLE; break; case GPUTOP_PERFQUERY_COUNTER_DATA_BOOL32: counter->data_type = GPUTOP__GLCOUNTER_DATA_TYPE__BOOL32; break; } counter->data_offset = c->data_offset; counters_vec[j] = counter; } query->data_size = q->max_counter_data_len; queries_vec[i] = query; i++; } } pthread_rwlock_unlock(&gputop_gl_lock); *n_queries_ret = n_queries; return queries_vec; } static void free_gl_query_info(Gputop__GLQueryInfo **queries, int n_queries) { for (int i = 0; i < n_queries; i++) { Gputop__GLQueryInfo *query = queries[i]; for (int j = 0; j < query->n_counters; j++) free(query->counters[j]); free(query->counters); free(query); } free(queries); } #endif static void handle_get_features(h2o_websocket_conn_t *conn, Gputop__Request *request) { char kernel_release[128]; char kernel_version[256]; char cpu_model[128]; Gputop__Message pb_message = GPUTOP__MESSAGE__INIT; Gputop__Features pb_features = GPUTOP__FEATURES__INIT; Gputop__DevInfo pb_devinfo = GPUTOP__DEV_INFO__INIT; Gputop__DevTopology pb_topology = GPUTOP__DEV_TOPOLOGY__INIT; char *notices[] = { "RC6 power saving mode disabled" }; if (!gputop_perf_initialize()) { pb_message.reply_uuid = request->uuid; pb_message.cmd_case = GPUTOP__MESSAGE__CMD_ERROR; pb_message.error = "Failed to initialize perf\n"; send_pb_message(conn, &pb_message.base); return; } pb_features.server_pid = getpid(); const struct gputop_devinfo *devinfo = gputop_perf_get_devinfo(); pb_devinfo.devid = devinfo->devid; pb_devinfo.gen = devinfo->gen; pb_devinfo.timestamp_frequency = devinfo->timestamp_frequency; pb_devinfo.gt_min_freq = devinfo->gt_min_freq; pb_devinfo.gt_max_freq = devinfo->gt_max_freq; pb_devinfo.devname = (char *) devinfo->devname; pb_devinfo.prettyname = (char *) devinfo->prettyname; const struct gputop_devtopology *devtopology = &devinfo->topology; pb_topology.max_slices = devtopology->max_slices; pb_topology.max_subslices = devtopology->max_subslices; pb_topology.max_eus_per_subslice = devtopology->max_eus_per_subslice; pb_topology.n_threads_per_eu = devtopology->n_threads_per_eu; pb_topology.slices_mask.len = ARRAY_SIZE(devtopology->slices_mask); pb_topology.slices_mask.data = (uint8_t *) devtopology->slices_mask; pb_topology.subslices_mask.len = ARRAY_SIZE(devtopology->subslices_mask); pb_topology.subslices_mask.data = (uint8_t *) devtopology->subslices_mask; pb_topology.eus_mask.len = ARRAY_SIZE(devtopology->eus_mask); pb_topology.eus_mask.data = (uint8_t *) devtopology->eus_mask; pb_topology.engines = (uint32_t *) devtopology->engines; pb_topology.n_engines = ARRAY_SIZE(devtopology->engines); pb_devinfo.topology = &pb_topology; pb_features.fake_mode = gputop_fake_mode; pb_features.has_i915_oa_cpu_timestamps = gputop_perf_kernel_has_i915_oa_cpu_timestamps(); pb_features.has_i915_oa_gpu_timestamps = gputop_perf_kernel_has_i915_oa_gpu_timestamps(); pb_features.devinfo = &pb_devinfo; #ifdef SUPPORT_GL pb_features.has_gl_performance_query = gputop_gl_has_intel_performance_query_ext; if (gputop_gl_has_intel_performance_query_ext && !gputop_fake_mode) { int n_gl_queries; pb_features.gl_queries = get_gl_query_info(&n_gl_queries); pb_features.n_gl_queries = n_gl_queries; } #else pb_features.has_gl_performance_query = false; #endif pb_features.has_i915_oa = true; pb_features.n_cpus = gputop_cpu_count(); gputop_cpu_model(cpu_model, sizeof(cpu_model)); string_rstrip(cpu_model); pb_features.cpu_model = cpu_model; pb_features.tracepoints = gputop_debugfs_get_tracepoint_names(); if (pb_features.tracepoints) { for (pb_features.n_tracepoints = 0; pb_features.tracepoints[pb_features.n_tracepoints]; pb_features.n_tracepoints++) { } } pb_features.events = gputop_get_events_names(); if (pb_features.events) { for (pb_features.n_events = 0; pb_features.events[pb_features.n_events]; pb_features.n_events++) { } } gputop_read_file("/proc/sys/kernel/osrelease", kernel_release, sizeof(kernel_release)); string_rstrip(kernel_release); gputop_read_file("/proc/sys/kernel/version", kernel_version, sizeof(kernel_version)); string_rstrip(kernel_version); pb_features.kernel_release = kernel_release; pb_features.kernel_build = kernel_version; pb_features.n_supported_oa_uuids = gputop_perf_oa_supported_metric_set_uuids->len; pb_features.supported_oa_uuids = gputop_perf_oa_supported_metric_set_uuids->data; pb_features.n_notices = ARRAY_SIZE(notices); pb_features.notices = notices; pb_message.reply_uuid = request->uuid; pb_message.cmd_case = GPUTOP__MESSAGE__CMD_FEATURES; pb_message.features = &pb_features; dbg("GPU:\n"); dbg(" Device ID = 0x%x\n", pb_devinfo.devid); dbg(" Gen = %"PRIu32"\n", pb_devinfo.gen); dbg(" EU Slice Count = %"PRIu64"\n", pb_devinfo.n_eu_slices); dbg(" EU Sub Slice Count = %"PRIu64"\n", pb_devinfo.n_eu_sub_slices); dbg(" EU Count (total) = %"PRIu64"\n", pb_devinfo.n_eus); dbg(" EU Threads Count (total) = %"PRIu64"\n", pb_devinfo.eu_threads_count); dbg(" Slice Mask = 0x%"PRIx64"\n", pb_devinfo.slice_mask); dbg(" Sub Slice Mask = 0x%"PRIx64"\n", pb_devinfo.subslice_mask); dbg(" OA Metrics Available = %s\n", pb_features.has_i915_oa ? "true" : "false"); dbg(" Timestamp Frequency = %"PRIu64"\n", pb_devinfo.timestamp_frequency); dbg(" Min Frequency = %"PRIu64"\n", pb_devinfo.gt_min_freq); dbg(" Max Frequency = %"PRIu64"\n", pb_devinfo.gt_max_freq); dbg("\n"); dbg("CPU:\n"); dbg(" Model = %s\n", pb_features.cpu_model); dbg(" Core Count = %u\n", pb_features.n_cpus); dbg("\n"); dbg("SYSTEM:\n"); dbg(" Kernel Release = %s\n", pb_features.kernel_release); dbg(" Kernel Build = %s\n", pb_features.kernel_build); dbg("NOTICES:\n"); for (int i = 0; i< pb_features.n_notices; i++) { MAYBE_UNUSED const char *notice = pb_features.notices[i]; dbg(" %s\n", notice); } send_pb_message(conn, &pb_message.base); gputop_debugfs_free_tracepoint_names(pb_features.tracepoints); gputop_free_events_names(pb_features.events); #ifdef SUPPORT_GL if (pb_features.n_gl_queries) free_gl_query_info(pb_features.gl_queries, pb_features.n_gl_queries); #endif } static void on_ws_message(h2o_websocket_conn_t *conn, const struct wslay_event_on_msg_recv_arg *arg) { Gputop__Request *request; //fprintf(stderr, "on_ws_message\n"); //dbg("on_ws_message\n"); if (arg == NULL) { //dbg("socket closed\n"); h2o_conn = NULL; terminate_all_streams(); h2o_websocket_close(conn); return; } if (wslay_is_ctrl_frame(arg->opcode)) return; request = (void *)protobuf_c_message_unpack(&gputop__request__descriptor, NULL, /* default allocator */ arg->msg_length, arg->msg); if (!request) { fprintf(stderr, "Failed to unpack message\n"); dbg("Failed to unpack message\n"); return; } switch (request->req_case) { case GPUTOP__REQUEST__REQ_GET_TRACEPOINT_INFO: server_dbg("GetTracepointInfo request received\n"); handle_get_tracepoint_info(conn, request); break; case GPUTOP__REQUEST__REQ_GET_PROCESS_INFO: server_dbg("GetProcessInfo request received\n"); handle_get_process_info(conn, request); break; case GPUTOP__REQUEST__REQ_GET_FEATURES: server_dbg("GetFeatures request received\n"); handle_get_features(conn, request); break; case GPUTOP__REQUEST__REQ_OPEN_STREAM: server_dbg("OpenStream request received\n"); handle_open_stream(conn, request); break; case GPUTOP__REQUEST__REQ_CLOSE_STREAM: server_dbg("CloseStream request received\n"); handle_close_stream(conn, request); break; case GPUTOP__REQUEST__REQ_TEST_LOG: server_dbg("TEST LOG: %s\n", request->test_log); break; case _GPUTOP__REQUEST__REQ_IS_INT_SIZE: server_dbg("TODO: INT_SIZE request\n"); break; case GPUTOP__REQUEST__REQ__NOT_SET: assert(0); } free(request); } static int on_req(h2o_handler_t *self, h2o_req_t *req) { const char *client_key; ssize_t proto_header_index; //dbg("on_req\n"); if (h2o_is_websocket_handshake(req, &client_key) != 0 || client_key == NULL) { return -1; } proto_header_index = h2o_find_header_by_str(&req->headers, "sec-websocket-protocol", strlen("sec-websocket-protocol"), SIZE_MAX); if (proto_header_index != -1) { //dbg("sec-websocket-protocols found\n"); h2o_add_header_by_str(&req->pool, &req->res.headers, "sec-websocket-protocol", strlen("sec-websocket-protocol"), 0, NULL, "binary", strlen("binary")); } h2o_conn = h2o_upgrade_to_websocket(req, client_key, NULL, on_ws_message); return 0; } static void on_connect(uv_stream_t *server, int status) { uv_tcp_t *conn; h2o_socket_t *sock; h2o_accept_ctx_t accept_ctx = { NULL, }; //dbg("on_connect\n"); if (status != 0) return; signal(SIGPIPE, SIG_IGN); conn = h2o_mem_alloc(sizeof(*conn)); uv_tcp_init(server->loop, conn); if (uv_accept(server, (uv_stream_t *)conn) != 0) { uv_close((uv_handle_t *)conn, (uv_close_cb)free); return; } sock = h2o_uv_socket_create((uv_stream_t *)conn, (uv_close_cb)free); accept_ctx.ctx = &ctx; accept_ctx.hosts = ctx.globalconf->hosts; accept_ctx.ssl_ctx = ssl_ctx; h2o_accept(&accept_ctx, sock); uv_timer_start(&timer, periodic_update_cb, 200, 200); } MAYBE_UNUSED static h2o_iovec_t cache_control; MAYBE_UNUSED static h2o_headers_command_t uncache_cmd[2]; static void gputop_server_print_addresses(unsigned long port) { struct ifaddrs *ifaddr, *ifa; char host[NI_MAXHOST]; size_t host_size = sizeof(host); printf("Web server listening on port %lu\n", port); if (getifaddrs(&ifaddr) == -1) { fprintf(stderr, "Unable to get network interfaces: %s\n", strerror(errno)); return; } if (uv_os_gethostname(host, &host_size) == 0) { printf("\tDefault : https://gputop.com?remoteHost=%s&remotePort=%lu\n", host, port); } for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { int s; if (ifa->ifa_addr == NULL) continue; s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if (ifa->ifa_addr->sa_family == AF_INET) { if (s != 0) { fprintf(stderr, "Unable to get interface '%s' ip address : %s\n", ifa->ifa_name, strerror(errno)); exit(EXIT_FAILURE); } printf("\tInterface '%s' : https://gputop.com?remoteHost=%s&remotePort=%lu\n", ifa->ifa_name, host, port); printf("\tInterface '%s' : gputop-ui -h %s:%lu\n", ifa->ifa_name, host, port); } } } bool gputop_server_run(void) { uv_loop_t *loop; struct sockaddr_in6 sockaddr; h2o_hostconf_t *hostconf; h2o_pathconf_t *pathconf; int r; char *port_env; unsigned long port; list_inithead(&streams); list_inithead(&closing_streams); loop = gputop_mainloop; uv_timer_init(gputop_mainloop, &timer); uv_idle_init(gputop_mainloop, &update_idle); if ((r = uv_tcp_init(loop, &listener)) != 0) { fprintf(stderr, "uv_tcp_init:%s\n", uv_strerror(r)); goto error; } port_env = getenv("GPUTOP_PORT"); if (!port_env) port_env = "7890"; port = strtoul(port_env, NULL, 10); uv_ip6_addr("::", port, &sockaddr); if ((r = uv_tcp_bind(&listener, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) != 0) { fprintf(stderr, "uv_tcp_bind:%s\n", uv_strerror(r)); goto error; } if ((r = uv_listen((uv_stream_t *)&listener, 128, on_connect)) != 0) { fprintf(stderr, "uv_listen:%s\n", uv_strerror(r)); goto error; } gputop_server_print_addresses(port); h2o_config_init(&config); hostconf = h2o_config_register_host(&config, h2o_iovec_init(H2O_STRLIT("default")), 7890); pathconf = h2o_config_register_path(hostconf, "/gputop", 0); h2o_create_handler(pathconf, sizeof(h2o_handler_t))->on_req = on_req; /* Without the web ui enabled we still support remote access to metrics via * a websocket + protocol buffers, we just don't host the web ui assets. */ #ifdef ENABLE_WEBUI h2o_pathconf_t *root = h2o_config_register_path(hostconf, "/", 0); const char *web_root = getenv("GPUTOP_WEB_ROOT"); if (!web_root) web_root = GPUTOP_WEB_ROOT; h2o_file_register(root, web_root, NULL, NULL, 0); cache_control = h2o_iovec_init(H2O_STRLIT("Cache-Control")); uncache_cmd[0].cmd = H2O_HEADERS_CMD_APPEND; uncache_cmd[0].name = &cache_control; uncache_cmd[0].value.base = "no-store"; uncache_cmd[0].value.len = strlen("no-store"); uncache_cmd[1].cmd = H2O_HEADERS_CMD_NULL; h2o_headers_register(root, uncache_cmd); #endif h2o_context_init(&ctx, loop, &config); /* disabled by default: uncomment the block below to use HTTPS instead of HTTP */ /* if (setup_ssl("server.crt", "server.key") != 0) goto Error; */ return true; error: return false; } ================================================ FILE: server/gputop-server.h ================================================ /* * GPU Top * * Copyright (C) 2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include bool gputop_server_run(void); ================================================ FILE: server/gputop-string.c ================================================ /* * String functions * * Author: * Miguel de Icaza (miguel@novell.com) * Aaron Bockover (abockover@novell.com) * * Copyright (C) 2006 Novell, Inc. * Copyright (C) 2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef EMSCRIPTEN #include #endif #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include #include #include #include #define GROW_IF_NECESSARY(s, l) \ { \ if (s->len + l >= s->allocated_len) { \ s->allocated_len = (s->allocated_len + l + 16) * 1.7; \ s->str = xrealloc(s->str, s->allocated_len); \ } \ } gputop_string_t * gputop_string_new_len(const char *init, ssize_t len) { gputop_string_t *ret = xmalloc(sizeof(*ret)); if (init == NULL) ret->len = 0; else ret->len = len < 0 ? strlen(init) : len; ret->allocated_len = MAX(ret->len + 1, 16); ret->str = xmalloc(ret->allocated_len); if (init) memcpy(ret->str, init, ret->len); ret->str[ret->len] = 0; return ret; } gputop_string_t * gputop_string_new(const char *init) { return gputop_string_new_len(init, -1); } gputop_string_t * gputop_string_sized_new(size_t default_size) { gputop_string_t *ret = xmalloc(sizeof(*ret)); ret->str = xmalloc(default_size); ret->str[0] = 0; ret->len = 0; ret->allocated_len = default_size; return ret; } char * gputop_string_free(gputop_string_t *string, bool free_segment) { char *data = string->str; free(string); if (!free_segment) { return data; } free(data); return NULL; } gputop_string_t * gputop_string_assign(gputop_string_t *string, const char *val) { if (string->str == val) return string; gputop_string_truncate(string, 0); gputop_string_append(string, val); return string; } gputop_string_t * gputop_string_append_len(gputop_string_t *string, const char *val, ssize_t len) { if (len < 0) len = strlen(val); GROW_IF_NECESSARY(string, len); memcpy(string->str + string->len, val, len); string->len += len; string->str[string->len] = 0; return string; } gputop_string_t * gputop_string_append(gputop_string_t *string, const char *val) { return gputop_string_append_len(string, val, -1); } gputop_string_t * gputop_string_append_c(gputop_string_t *string, char c) { GROW_IF_NECESSARY(string, 1); string->str[string->len] = c; string->str[string->len + 1] = 0; string->len++; return string; } gputop_string_t * gputop_string_prepend(gputop_string_t *string, const char *val) { ssize_t len = strlen(val); GROW_IF_NECESSARY(string, len); memmove(string->str + len, string->str, string->len + 1); memcpy(string->str, val, len); return string; } gputop_string_t * gputop_string_insert(gputop_string_t *string, ssize_t pos, const char *val) { ssize_t len = strlen(val); GROW_IF_NECESSARY(string, len); memmove(string->str + pos + len, string->str + pos, string->len - pos - len + 1); memcpy(string->str + pos, val, len); return string; } static char * strdup_vprintf(const char *format, va_list args) { int n; char *ret; n = vasprintf(&ret, format, args); if (n == -1) return NULL; return ret; } void gputop_string_append_printf(gputop_string_t *string, const char *format, ...) { char *ret; va_list args; va_start(args, format); ret = strdup_vprintf(format, args); va_end(args); gputop_string_append(string, ret); free(ret); } void gputop_string_append_vprintf(gputop_string_t *string, const char *format, va_list args) { char *ret; ret = strdup_vprintf(format, args); gputop_string_append(string, ret); free(ret); } void gputop_string_printf(gputop_string_t *string, const char *format, ...) { va_list args; free(string->str); va_start(args, format); string->str = strdup_vprintf(format, args); va_end(args); string->len = strlen(string->str); string->allocated_len = string->len + 1; } gputop_string_t * gputop_string_truncate(gputop_string_t *string, size_t len) { /* Silent return */ if (len >= string->len) return string; string->len = len; string->str[len] = 0; return string; } gputop_string_t * gputop_string_set_size(gputop_string_t *string, size_t len) { GROW_IF_NECESSARY(string, len); string->len = len; string->str[len] = 0; return string; } gputop_string_t * gputop_string_erase(gputop_string_t *string, ssize_t pos, ssize_t len) { /* Silent return */ if (pos >= string->len) return string; if (len == -1 || (pos + len) >= string->len) { string->str[pos] = 0; } else { memmove(string->str + pos, string->str + pos + len, string->len - (pos + len) + 1); string->len -= len; } return string; } gputop_string_t * gputop_string_append_escaped(gputop_string_t *str, const char *_str) { int i; for (i = 0; _str[i]; i++) { char c = _str[i]; switch (c) { case '"': gputop_string_append_len(str, "\"", 2); break; case '\\': gputop_string_append_len(str, "\\\\", 2); break; case '\b': gputop_string_append_len(str, "\\b", 2); break; case '\f': gputop_string_append_len(str, "\\f", 2); break; case '\n': gputop_string_append_len(str, "\\n", 2); break; case '\r': gputop_string_append_len(str, "\\r", 2); break; case '\t': gputop_string_append_len(str, "\\t", 2); break; default: gputop_string_append_c(str, c); } } return str; } ================================================ FILE: server/gputop-string.h ================================================ /* * GPU Top * * Copyright (C) 2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include typedef struct { char *str; size_t len; size_t allocated_len; } gputop_string_t; gputop_string_t *gputop_string_new(const char *init); gputop_string_t *gputop_string_new_len(const char *init, ssize_t len); gputop_string_t *gputop_string_sized_new(size_t default_size); char *gputop_string_free(gputop_string_t *string, bool free_segment); gputop_string_t *gputop_string_assign(gputop_string_t *string, const char *val); gputop_string_t *gputop_string_append(gputop_string_t *string, const char *val); void gputop_string_printf(gputop_string_t *string, const char *format, ...); void gputop_string_append_printf(gputop_string_t *string, const char *format, ...); void gputop_string_append_vprintf(gputop_string_t *string, const char *format, va_list args); gputop_string_t *gputop_string_append_c(gputop_string_t *string, char c); gputop_string_t *gputop_string_append(gputop_string_t *string, const char *val); gputop_string_t *gputop_string_append_len(gputop_string_t *string, const char *val, ssize_t len); gputop_string_t *gputop_string_truncate(gputop_string_t *string, size_t len); gputop_string_t *gputop_string_prepend(gputop_string_t *string, const char *val); gputop_string_t *gputop_string_insert(gputop_string_t *string, ssize_t pos, const char *val); gputop_string_t *gputop_string_set_size(gputop_string_t *string, size_t len); gputop_string_t *gputop_string_erase(gputop_string_t *string, ssize_t pos, ssize_t len); gputop_string_t *gputop_string_append_escaped(gputop_string_t *str, const char *_str); #define gputop_string_sprintfa gputop_string_append_printf ================================================ FILE: server/gputop-system.c ================================================ #include /* For the sake of consistently running gputop with respect to a test * application; this is essentially a test application that does * nothing interesting itself that can be used while investigating * system-wide metrics. * * Note that gputop-system is linked against libgputop.so and the ui * will be initialized/run via a library constructor (gputop_ui_init) */ int main(int argc, char **argv) { while (1) sleep(60); return 0; } ================================================ FILE: server/gputop-sysutil.c ================================================ /* * GPU Top * * Copyright (C) 2014,2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include #include #include #include "gputop-sysutil.h" bool gputop_get_bool_env(const char *var) { char *val = getenv(var); if (!val) return false; if (strcmp(val, "1") == 0 || strcasecmp(val, "yes") == 0 || strcasecmp(val, "on") == 0 || strcasecmp(val, "true") == 0) return true; else if (strcmp(val, "0") == 0 || strcasecmp(val, "no") == 0 || strcasecmp(val, "off") == 0 || strcasecmp(val, "false") == 0) return false; fprintf(stderr, "unrecognised value for boolean variable %s\n", var); return false; } uint64_t gputop_get_time(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000000000 + (uint64_t)t.tv_nsec; } bool gputop_read_file(const char *filename, void *buf, int max) { int fd; int n; memset(buf, 0, max); fd = open(filename, 0); if (fd < 0) return false; n = read(fd, buf, max - 1); close(fd); if (n < 0) return false; return true; } ================================================ FILE: server/gputop-sysutil.h ================================================ /* * GPU Top * * Copyright (C) 2014 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include #include #include #include #include #include #include #include #include bool gputop_get_bool_env(const char *var); uint64_t gputop_get_time(void); bool gputop_read_file(const char *filename, void *buf, int max); static bool __attribute__((unused)) gputop_read_file_uint64(const char *file, uint64_t *value) { char buf[32]; int fd, n; fd = open(file, 0); if (fd < 0) return false; n = read(fd, buf, sizeof (buf) - 1); close(fd); if (n < 0) return false; buf[n] = '\0'; *value = strtoull(buf, 0, 0); return true; } ================================================ FILE: server/meson.build ================================================ libgputop_src = [ 'gputop-perf.c', 'gputop-sysutil.c', 'gputop-log.c', 'gputop-ncurses.c', 'gputop-cpu.c', 'gputop-debugfs.c', 'gputop-ioctl.c', 'gputop-server.c', ] libgputop_inc = include_directories('.') gputop_deps = [ dependency('threads'), cc.find_library('dl', required: false), libuv_dep, wslay_dep, h2o_dep, protobuf_c_dep, ] gputop_deps += [ gputop_client_dep, mesa_dep, ] gputop_flags = [ '-DHAVE_PTHREAD', '-D_GNU_SOURCE' ] config_h = custom_target('config.h', input : [], output : ['config.h'], command : [find_program('touch'), '@OUTPUT@']) libgputop = shared_library('gputop', [libgputop_src, config_h], c_args : gputop_flags, dependencies : gputop_deps, include_directories : libgputop_inc, install : true) gputop_system_src = [ 'gputop-system.c', ] executable('gputop-system', [gputop_system_src, config_h], include_directories : libgputop_inc, link_with : libgputop, install : true) gputop_src = [ 'gputop-main.c', ] executable('gputop', [gputop_src, config_h], c_args : gputop_flags, include_directories : libgputop_inc, link_with : libgputop, dependencies: mesa_dep, install : true) ================================================ FILE: server/registry/.gitignore ================================================ eglapi.c glapi.c glxapi.c ================================================ FILE: server/registry/egl.xml ================================================ #include <KHR/khrplatform.h> #include <EGL/eglplatform.h> typedef unsigned int EGLBoolean; typedef unsigned int EGLenum; typedef intptr_t EGLAttribKHR; typedef intptr_t EGLAttrib; typedef void *EGLClientBuffer; typedef void *EGLConfig; typedef void *EGLContext; typedef void *EGLDeviceEXT; typedef void *EGLDisplay; typedef void *EGLImage; typedef void *EGLImageKHR; typedef void *EGLOutputLayerEXT; typedef void *EGLOutputPortEXT; typedef void *EGLStreamKHR; typedef void *EGLSurface; typedef void *EGLSync; typedef void *EGLSyncKHR; typedef void *EGLSyncNV; typedef void (*__eglMustCastToProperFunctionPointerType)(void); typedef khronos_utime_nanoseconds_t EGLTimeKHR; typedef khronos_utime_nanoseconds_t EGLTime; typedef khronos_utime_nanoseconds_t EGLTimeNV; typedef khronos_utime_nanoseconds_t EGLuint64NV; typedef khronos_uint64_t EGLuint64KHR; typedef int EGLNativeFileDescriptorKHR; typedef khronos_ssize_t EGLsizeiANDROID; typedef void (*EGLSetBlobFuncANDROID) (const void *key, EGLsizeiANDROID keySize, const void *value, EGLsizeiANDROID valueSize); typedef EGLsizeiANDROID (*EGLGetBlobFuncANDROID) (const void *key, EGLsizeiANDROID keySize, void *value, EGLsizeiANDROID valueSize); struct EGLClientPixmapHI { void *pData; EGLint iWidth; EGLint iHeight; EGLint iStride; }; EGLBoolean eglBindAPI EGLenum api EGLBoolean eglBindTexImage EGLDisplay dpy EGLSurface surface EGLint buffer EGLBoolean eglChooseConfig EGLDisplay dpy const EGLint *attrib_list EGLConfig *configs EGLint config_size EGLint *num_config EGLint eglClientWaitSync EGLDisplay dpy EGLSync sync EGLint flags EGLTime timeout EGLint eglClientWaitSyncKHR EGLDisplay dpy EGLSyncKHR sync EGLint flags EGLTimeKHR timeout EGLint eglClientWaitSyncNV EGLSyncNV sync EGLint flags EGLTimeNV timeout EGLBoolean eglCopyBuffers EGLDisplay dpy EGLSurface surface EGLNativePixmapType target EGLContext eglCreateContext EGLDisplay dpy EGLConfig config EGLContext share_context const EGLint *attrib_list EGLImageKHR eglCreateDRMImageMESA EGLDisplay dpy const EGLint *attrib_list EGLSyncNV eglCreateFenceSyncNV EGLDisplay dpy EGLenum condition const EGLint *attrib_list EGLImage eglCreateImage EGLDisplay dpy EGLContext ctx EGLenum target EGLClientBuffer buffer const EGLint *attrib_list EGLImageKHR eglCreateImageKHR EGLDisplay dpy EGLContext ctx EGLenum target EGLClientBuffer buffer const EGLint *attrib_list EGLSurface eglCreatePbufferFromClientBuffer EGLDisplay dpy EGLenum buftype EGLClientBuffer buffer EGLConfig config const EGLint *attrib_list EGLSurface eglCreatePbufferSurface EGLDisplay dpy EGLConfig config const EGLint *attrib_list EGLSurface eglCreatePixmapSurface EGLDisplay dpy EGLConfig config EGLNativePixmapType pixmap const EGLint *attrib_list EGLSurface eglCreatePixmapSurfaceHI EGLDisplay dpy EGLConfig config struct EGLClientPixmapHI *pixmap EGLSurface eglCreatePlatformPixmapSurface EGLDisplay dpy EGLConfig config void *native_pixmap const EGLAttrib *attrib_list EGLSurface eglCreatePlatformPixmapSurfaceEXT EGLDisplay dpy EGLConfig config void *native_pixmap const EGLint *attrib_list EGLSurface eglCreatePlatformWindowSurface EGLDisplay dpy EGLConfig config void *native_window const EGLAttrib *attrib_list EGLSurface eglCreatePlatformWindowSurfaceEXT EGLDisplay dpy EGLConfig config void *native_window const EGLint *attrib_list EGLStreamKHR eglCreateStreamFromFileDescriptorKHR EGLDisplay dpy EGLNativeFileDescriptorKHR file_descriptor EGLStreamKHR eglCreateStreamKHR EGLDisplay dpy const EGLint *attrib_list EGLSurface eglCreateStreamProducerSurfaceKHR EGLDisplay dpy EGLConfig config EGLStreamKHR stream const EGLint *attrib_list EGLSyncKHR eglCreateStreamSyncNV EGLDisplay dpy EGLStreamKHR stream EGLenum type const EGLint *attrib_list EGLSync eglCreateSync EGLDisplay dpy EGLenum type const EGLAttrib *attrib_list EGLSyncKHR eglCreateSyncKHR EGLDisplay dpy EGLenum type const EGLint *attrib_list EGLSyncKHR eglCreateSync64KHR EGLDisplay dpy EGLenum type const EGLAttribKHR *attrib_list EGLSurface eglCreateWindowSurface EGLDisplay dpy EGLConfig config EGLNativeWindowType win const EGLint *attrib_list EGLBoolean eglDestroyContext EGLDisplay dpy EGLContext ctx EGLBoolean eglDestroyImage EGLDisplay dpy EGLImage image EGLBoolean eglDestroyImageKHR EGLDisplay dpy EGLImageKHR image EGLBoolean eglDestroyStreamKHR EGLDisplay dpy EGLStreamKHR stream EGLBoolean eglDestroySurface EGLDisplay dpy EGLSurface surface EGLBoolean eglDestroySync EGLDisplay dpy EGLSync sync EGLBoolean eglDestroySyncKHR EGLDisplay dpy EGLSyncKHR sync EGLBoolean eglDestroySyncNV EGLSyncNV sync EGLint eglDupNativeFenceFDANDROID EGLDisplay dpy EGLSyncKHR sync EGLBoolean eglExportDRMImageMESA EGLDisplay dpy EGLImageKHR image EGLint *name EGLint *handle EGLint *stride EGLBoolean eglFenceNV EGLSyncNV sync EGLBoolean eglGetConfigAttrib EGLDisplay dpy EGLConfig config EGLint attribute EGLint *value EGLBoolean eglGetConfigs EGLDisplay dpy EGLConfig *configs EGLint config_size EGLint *num_config EGLContext eglGetCurrentContext EGLDisplay eglGetCurrentDisplay EGLSurface eglGetCurrentSurface EGLint readdraw EGLDisplay eglGetDisplay EGLNativeDisplayType display_id EGLint eglGetError EGLBoolean eglGetOutputLayersEXT EGLDisplay dpy const EGLAttrib *attrib_list EGLOutputLayerEXT *layers EGLint max_layers EGLint *num_layers EGLBoolean eglGetOutputPortsEXT EGLDisplay dpy const EGLAttrib *attrib_list EGLOutputPortEXT *ports EGLint max_ports EGLint *num_ports EGLDisplay eglGetPlatformDisplay EGLenum platform void *native_display const EGLAttrib *attrib_list EGLDisplay eglGetPlatformDisplayEXT EGLenum platform void *native_display const EGLint *attrib_list __eglMustCastToProperFunctionPointerType eglGetProcAddress const char *procname EGLNativeFileDescriptorKHR eglGetStreamFileDescriptorKHR EGLDisplay dpy EGLStreamKHR stream EGLBoolean eglGetSyncAttrib EGLDisplay dpy EGLSync sync EGLint attribute EGLAttrib *value EGLBoolean eglGetSyncAttribKHR EGLDisplay dpy EGLSyncKHR sync EGLint attribute EGLint *value EGLBoolean eglGetSyncAttribNV EGLSyncNV sync EGLint attribute EGLint *value EGLuint64NV eglGetSystemTimeFrequencyNV EGLuint64NV eglGetSystemTimeNV EGLBoolean eglInitialize EGLDisplay dpy EGLint *major EGLint *minor EGLBoolean eglLockSurfaceKHR EGLDisplay dpy EGLSurface surface const EGLint *attrib_list EGLBoolean eglMakeCurrent EGLDisplay dpy EGLSurface draw EGLSurface read EGLContext ctx EGLBoolean eglOutputLayerAttribEXT EGLDisplay dpy EGLOutputLayerEXT layer EGLint attribute EGLAttrib value EGLBoolean eglOutputPortAttribEXT EGLDisplay dpy EGLOutputPortEXT port EGLint attribute EGLAttrib value EGLBoolean eglPostSubBufferNV EGLDisplay dpy EGLSurface surface EGLint x EGLint y EGLint width EGLint height EGLenum eglQueryAPI EGLBoolean eglQueryContext EGLDisplay dpy EGLContext ctx EGLint attribute EGLint *value EGLBoolean eglQueryDeviceAttribEXT EGLDeviceEXT device EGLint attribute EGLAttrib *value const char *eglQueryDeviceStringEXT EGLDeviceEXT device EGLint name EGLBoolean eglQueryDevicesEXT EGLint max_devices EGLDeviceEXT *devices EGLint *num_devices EGLBoolean eglQueryDisplayAttribEXT EGLDisplay dpy EGLint attribute EGLAttrib *value EGLBoolean eglQueryNativeDisplayNV EGLDisplay dpy EGLNativeDisplayType *display_id EGLBoolean eglQueryNativePixmapNV EGLDisplay dpy EGLSurface surf EGLNativePixmapType *pixmap EGLBoolean eglQueryNativeWindowNV EGLDisplay dpy EGLSurface surf EGLNativeWindowType *window EGLBoolean eglQueryOutputLayerAttribEXT EGLDisplay dpy EGLOutputLayerEXT layer EGLint attribute EGLAttrib *value const char *eglQueryOutputLayerStringEXT EGLDisplay dpy EGLOutputLayerEXT layer EGLint name EGLBoolean eglQueryOutputPortAttribEXT EGLDisplay dpy EGLOutputPortEXT port EGLint attribute EGLAttrib *value const char *eglQueryOutputPortStringEXT EGLDisplay dpy EGLOutputPortEXT port EGLint name EGLBoolean eglQueryStreamKHR EGLDisplay dpy EGLStreamKHR stream EGLenum attribute EGLint *value EGLBoolean eglQueryStreamTimeKHR EGLDisplay dpy EGLStreamKHR stream EGLenum attribute EGLTimeKHR *value EGLBoolean eglQueryStreamu64KHR EGLDisplay dpy EGLStreamKHR stream EGLenum attribute EGLuint64KHR *value const char *eglQueryString EGLDisplay dpy EGLint name EGLBoolean eglQuerySurface EGLDisplay dpy EGLSurface surface EGLint attribute EGLint *value EGLBoolean eglQuerySurface64KHR EGLDisplay dpy EGLSurface surface EGLint attribute EGLAttribKHR *value EGLBoolean eglQuerySurfacePointerANGLE EGLDisplay dpy EGLSurface surface EGLint attribute void **value EGLBoolean eglReleaseTexImage EGLDisplay dpy EGLSurface surface EGLint buffer EGLBoolean eglReleaseThread void eglSetBlobCacheFuncsANDROID EGLDisplay dpy EGLSetBlobFuncANDROID set EGLGetBlobFuncANDROID get EGLBoolean eglSignalSyncKHR EGLDisplay dpy EGLSyncKHR sync EGLenum mode EGLBoolean eglSignalSyncNV EGLSyncNV sync EGLenum mode EGLBoolean eglStreamAttribKHR EGLDisplay dpy EGLStreamKHR stream EGLenum attribute EGLint value EGLBoolean eglStreamConsumerAcquireKHR EGLDisplay dpy EGLStreamKHR stream EGLBoolean eglStreamConsumerGLTextureExternalKHR EGLDisplay dpy EGLStreamKHR stream EGLBoolean eglStreamConsumerOutputEXT EGLDisplay dpy EGLStreamKHR stream EGLOutputLayerEXT layer EGLBoolean eglStreamConsumerReleaseKHR EGLDisplay dpy EGLStreamKHR stream EGLBoolean eglSurfaceAttrib EGLDisplay dpy EGLSurface surface EGLint attribute EGLint value EGLBoolean eglSwapBuffers EGLDisplay dpy EGLSurface surface EGLBoolean eglSwapBuffersWithDamageEXT EGLDisplay dpy EGLSurface surface EGLint *rects EGLint n_rects EGLBoolean eglSwapBuffersRegionNOK EGLDisplay dpy EGLSurface surface EGLint numRects const EGLint *rects EGLBoolean eglSwapBuffersRegion2NOK EGLDisplay dpy EGLSurface surface EGLint numRects const EGLint *rects EGLBoolean eglSwapInterval EGLDisplay dpy EGLint interval EGLBoolean eglTerminate EGLDisplay dpy EGLBoolean eglUnlockSurfaceKHR EGLDisplay dpy EGLSurface surface EGLBoolean eglWaitClient EGLBoolean eglWaitGL EGLBoolean eglWaitNative EGLint engine EGLBoolean eglWaitSync EGLDisplay dpy EGLSync sync EGLint flags EGLint eglWaitSyncKHR EGLDisplay dpy EGLSyncKHR sync EGLint flags ================================================ FILE: server/registry/genapis.py ================================================ #!/usr/bin/env python2 # # Copyright (c) 2013-2014 The Khronos Group Inc. # Copyright (c) 2014 Intel Corporation # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and/or associated documentation files (the # "Materials"), to deal in the Materials without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Materials, and to # permit persons to whom the Materials are furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Materials. # # THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. import sys, time, pdb, string, cProfile from reg import * import argparse # debug - start header generation in debugger # profile - enable Python profiling # timeit - time length of registry loading & header generation debug = False profile = False timeit = False # Default input / log files errFilename = None diagFilename = 'diag.txt' class ShimGeneratorOptions(CGeneratorOptions): """Represents options during C header production from an API registry""" def __init__(self, xmlfile = None, filename = None, apiname = None, hooks = set(), profile = None, versions = '.*', emitversions = '.*', defaultExtensions = None, addExtensions = None, removeExtensions = None, sortProcedure = regSortFeatures, prefixText = ''): CGeneratorOptions.__init__(self, filename, apiname, profile, versions, emitversions, defaultExtensions) self.xmlfile = xmlfile self.prefixText = prefixText self.hooks = hooks class ShimOutputGenerator(COutputGenerator): """Generate specified API interfaces in a specific style, such as a C header""" def __init__(self, errFile = sys.stderr, warnFile = sys.stderr, diagFile = sys.stdout): COutputGenerator.__init__(self, errFile, warnFile, diagFile) # Internal state - accumulators for different inner block text self.typeBody = '' self.enumBody = '' self.cmdBody = '' def makeProto(self, cmd, namePrefix = ''): proto = cmd.find('proto') params = cmd.findall('param') protostr = '' name = '' protostr += noneStr(proto.text) for elem in proto: text = noneStr(elem.text) tail = noneStr(elem.tail) if (elem.tag == 'name'): name = text protostr += namePrefix + text + tail else: protostr += text + tail n = len(params) protostr += ' (' if n > 0: for i in range(0,n): protostr += ''.join([t for t in params[i].itertext()]) if (i < n - 1): protostr += ', ' else: protostr += 'void' protostr += ")" return protostr def makeHook(self, cmd): proto = cmd.find('proto') params = cmd.findall('param') hook = '' name = '' for elem in proto: if (elem.tag == 'name'): name = noneStr(elem.text) hook += self.makeProto(cmd, namePrefix = "gputop_") + ";\n"; hook += self.makeProto(cmd) hook += "\n{\n"; hook += " " ret = proto.find('ptype') if ret != None: hook += "return " hook += "gputop_" + name + " (" n = len(params) if n > 0: for i in range(0,n): hook += params[i].find('name').text if (i < n - 1): hook += ', ' hook += ");\n" hook += "}\n\n" return hook def makeShim(self, cmd): """Generate shim function for Element""" proto = cmd.find('proto') shim = '' name = '' for elem in proto: if (elem.tag == 'name'): name = noneStr(elem.text) if (name in self.genOpts.hooks): shim += self.makeHook(cmd) return shim # def newline(self): write('', file=self.outFile) # def beginFile(self, genOpts): OutputGenerator.beginFile(self, genOpts) # User-supplied prefix text, if any (list of strings) if (genOpts.prefixText): for s in genOpts.prefixText: write(s, file=self.outFile) #write(passthroughResolver, file=self.outFile) def endFile(self): self.newline() OutputGenerator.endFile(self) def beginFeature(self, interface, emit): # Start processing in superclass OutputGenerator.beginFeature(self, interface, emit) # Accumulate function shims to print in endFeature() self.cmdBody = '' self.typeBody = '' self.featureExtraProtect = interface.get('protect') def endFeature(self): # Actually write the interface to the output file. if (self.emit): self.newline() if (self.featureExtraProtect != None): write('#ifdef', self.featureExtraProtect, file=self.outFile) #if (self.cmdBody != '' or self.typeBody != ''): if (self.cmdBody != ''): write('/* ', self.featureName, ' */', file=self.outFile) #write(self.typeBody, end='', file=self.outFile) write(self.cmdBody, end='', file=self.outFile) if (self.featureExtraProtect != None): write('#endif', file=self.outFile) # Finish processing in superclass OutputGenerator.endFeature(self) # # Type generation def genType(self, typeinfo, name): OutputGenerator.genType(self, typeinfo, name) # # Replace tags with an APIENTRY-style string # (from self.genOpts). Copy other text through unchanged. # If the resulting text is an empty string, don't emit it. typeElem = typeinfo.elem s = noneStr(typeElem.text) for elem in typeElem: if (elem.tag == 'apientry'): s += noneStr(elem.tail) else: s += noneStr(elem.text) + noneStr(elem.tail) if (len(s) > 0): self.typeBody += s + "\n" # # Enumerant generation def genEnum(self, enuminfo, name): OutputGenerator.genEnum(self, enuminfo, name) # # Command generation def genCmd(self, cmdinfo, name): OutputGenerator.genCmd(self, cmdinfo, name) self.cmdBody += self.makeShim(cmdinfo.elem) if __name__ == '__main__': i = 1 while (i < len(sys.argv)): arg = sys.argv[i] i = i + 1 if (arg == '-debug'): write('Enabling debug (-debug)', file=sys.stderr) debug = True elif (arg == '-profile'): write('Enabling profiling (-profile)', file=sys.stderr) profile = True elif (arg == '-time'): write('Enabling timing (-time)', file=sys.stderr) timeit = True elif (arg[0:1] == '-'): write('Unrecognized argument:', arg, file=sys.stderr) exit(1) parser = argparse.ArgumentParser() parser.add_argument("registry", help="Location of Khronos API XML files") parser.add_argument("--debug", dest='debug', action='store_true', help="Enable debug") parser.add_argument("--profile", dest='profile', action='store_true', help="Enable profile") parser.add_argument("--timing", dest='timeit', action='store_true', help="Enable timing") args = parser.parse_args() # Simple timer functions startTime = None def startTimer(): global startTime startTime = time.clock() def endTimer(msg): global startTime endTime = time.clock() if (timeit): write(msg, endTime - startTime) startTime = None # Turn a list of strings into a regexp string matching exactly those strings def makeREstring(list): return '^(' + '|'.join(list) + ')$' # Descriptive names for various regexp patterns used to select # versions and extensions allVersions = allExtensions = '.*' noVersions = noExtensions = None gl12andLaterPat = '1\.[2-9]|[234]\.[0-9]' gles2onlyPat = '2\.[0-9]' gles2and30Pat = '2\.[0-9]|3.0' gles2and30and31Pat = '2.[0-9]|3.[01]' # Extensions in old glcorearb.h but not yet tagged accordingly in gl.xml glCoreARBPat = None glx13andLaterPat = '1\.[3-9]' prefixStrings = [ '/* DON\'T EDIT THIS FILE IT WAS AUTOMATICALLY GENERATED BY genshims.py */', '' ] # glext.h / glcorearb.h define calling conventions inline (no GL *platform.h) # GLES 1/2/3 core .h have separate *platform.h files to define calling conventions gles2PlatformStrings = [ '#include ', '' ] gles3PlatformStrings = [ '#include ', '' ] eglPlatformStrings = [ '#include ', '' ] # GLES 1/2 extension .h have small addition to calling convention headers gles2ExtPlatformStrings = [ '#ifndef GL_APIENTRYP', '#define GL_APIENTRYP GL_APIENTRY*', '#endif', '' ] # Insert generation date in a comment for headers not having *GLEXT_VERSION macros genDateCommentString = [ format("/* Generated on date %s */" % time.strftime("%Y%m%d")), '' ] # GL_GLEXT_VERSION is defined only in glext.h glextVersionStrings = [ format("#define GL_GLEXT_VERSION %s" % time.strftime("%Y%m%d")), '' ] # GLX_GLXEXT_VERSION is defined only in glxext.h glxextVersionStrings = [ format("#define GLX_GLXEXT_VERSION %s" % time.strftime("%Y%m%d")), '' ] # EGL_EGLEXT_VERSION is defined only in eglext.h eglextVersionStrings = [ format("#define EGL_EGLEXT_VERSION %s" % time.strftime("%Y%m%d")), '' ] glapiHooks = { 'glGetError', 'glEnable', 'glDisable', 'glScissor', 'glDebugMessageControl', 'glDebugMessageCallback' } glxapiHooks = { 'glXGetProcAddress', 'glXGetProcAddressARB', 'glXMakeCurrent', 'glXMakeContextCurrent', 'glXSwapBuffers', 'glXCreateContext', 'glXCreateNewContext', 'glXCreateContextAttribsARB', 'glXDestroyContext', 'glXQueryExtension' } glxapiHeaders = [ '#include ', '' ] glapiHeaders = [ '#include ', '' ] eglapiHeaders = [ '#include ', '' ] buildList = [ # GL API 1.2+ + extensions ShimGeneratorOptions( xmlfile = 'gl.xml', filename = 'glapi.c', apiname = 'gl', hooks = glapiHooks, profile = 'compatibility', versions = allVersions, emitversions = allVersions, defaultExtensions = 'gl', addExtensions = None, removeExtensions = None, prefixText = prefixStrings + glextVersionStrings + glapiHeaders), # GLX 1.* API ShimGeneratorOptions( xmlfile = 'glx.xml', filename = 'glxapi.c', apiname = 'glx', hooks = glxapiHooks, profile = None, versions = allVersions, emitversions = allVersions, defaultExtensions = 'glx', addExtensions = None, removeExtensions = None, # add glXPlatformStrings? prefixText = prefixStrings + genDateCommentString + glxapiHeaders), # EGL API ShimGeneratorOptions( xmlfile = 'egl.xml', filename = 'eglapi.c', apiname = 'egl', profile = None, versions = allVersions, emitversions = allVersions, defaultExtensions = 'egl', addExtensions = None, removeExtensions = None, prefixText = prefixStrings + eglPlatformStrings + genDateCommentString + eglapiHeaders), # End of list None ] # create error/warning & diagnostic files if (errFilename): errWarn = open(errFilename,'w') else: errWarn = sys.stderr diag = open(diagFilename, 'w') def genShims(): generated = 0 for genOpts in buildList: if (genOpts == None): break # Load & parse registry reg = Registry() startTimer() tree = etree.parse(args.registry + '/' + genOpts.xmlfile) endTimer('Time to make ElementTree =') startTimer() reg.loadElementTree(tree) endTimer('Time to parse ElementTree =') write('*** Building', genOpts.filename) generated = generated + 1 startTimer() gen = ShimOutputGenerator(errFile=errWarn, warnFile=errWarn, diagFile=diag) reg.setGenerator(gen) reg.apiGen(genOpts) write('** Generated', genOpts.filename) endTimer('Time to generate ' + genOpts.filename + ' =') if (debug): pdb.run('genShims()') elif (profile): import cProfile, pstats cProfile.run('genShims()', 'profile.txt') p = pstats.Stats('profile.txt') p.strip_dirs().sort_stats('time').print_stats(50) else: genShims() ================================================ FILE: server/registry/gl.xml ================================================ Copyright (c) 2013-2014 The Khronos Group Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and/or associated documentation files (the "Materials"), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials, and to permit persons to whom the Materials are furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Materials. THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. ------------------------------------------------------------------------ This file, gl.xml, is the OpenGL and OpenGL API Registry. The older ".spec" file format has been retired and will no longer be updated with new extensions and API versions. The canonical version of the registry, together with documentation, schema, and Python generator scripts used to generate C header files for OpenGL and OpenGL ES, can always be found in the Khronos Registry at http://www.opengl.org/registry/ #include <stddef.h> #include <KHR/khrplatform.h> #ifndef GLEXT_64_TYPES_DEFINED /* This code block is duplicated in glxext.h, so must be protected */ #define GLEXT_64_TYPES_DEFINED /* Define int32_t, int64_t, and uint64_t types for UST/MSC */ /* (as used in the GL_EXT_timer_query extension). */ #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #include <inttypes.h> #elif defined(__sun__) || defined(__digital__) #include <inttypes.h> #if defined(__STDC__) #if defined(__arch64__) || defined(_LP64) typedef long int int64_t; typedef unsigned long int uint64_t; #else typedef long long int int64_t; typedef unsigned long long int uint64_t; #endif /* __arch64__ */ #endif /* __STDC__ */ #elif defined( __VMS ) || defined(__sgi) #include <inttypes.h> #elif defined(__SCO__) || defined(__USLC__) #include <stdint.h> #elif defined(__UNIXOS2__) || defined(__SOL64__) typedef long int int32_t; typedef long long int int64_t; typedef unsigned long long int uint64_t; #elif defined(_WIN32) && defined(__GNUC__) #include <stdint.h> #elif defined(_WIN32) typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #else /* Fallback if nothing above works */ #include <inttypes.h> #endif #endif typedef unsigned int GLenum; typedef unsigned char GLboolean; typedef unsigned int GLbitfield; typedef void GLvoid; typedef signed char GLbyte; typedef short GLshort; typedef int GLint; typedef int GLclampx; typedef unsigned char GLubyte; typedef unsigned short GLushort; typedef unsigned int GLuint; typedef int GLsizei; typedef float GLfloat; typedef float GLclampf; typedef double GLdouble; typedef double GLclampd; typedef void *GLeglImageOES; typedef char GLchar; typedef char GLcharARB; #ifdef __APPLE__ typedef void *GLhandleARB; #else typedef unsigned int GLhandleARB; #endif typedef unsigned short GLhalfARB; typedef unsigned short GLhalf; typedef GLint GLfixed; typedef ptrdiff_t GLintptr; typedef ptrdiff_t GLsizeiptr; typedef int64_t GLint64; typedef uint64_t GLuint64; typedef ptrdiff_t GLintptrARB; typedef ptrdiff_t GLsizeiptrARB; typedef int64_t GLint64EXT; typedef uint64_t GLuint64EXT; typedef struct __GLsync *GLsync; struct _cl_context; struct _cl_event; typedef void ( *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void ( *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void ( *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef khronos_int32_t GLclampx; typedef khronos_int8_t GLbyte; typedef khronos_uint8_t GLubyte; typedef khronos_float_t GLfloat; typedef khronos_float_t GLclampf; typedef khronos_int32_t GLfixed; typedef khronos_int64_t GLint64; typedef khronos_uint64_t GLuint64; typedef khronos_intptr_t GLintptr; typedef khronos_ssize_t GLsizeiptr; typedef khronos_int8_t GLbyte; typedef khronos_uint8_t GLubyte; typedef khronos_float_t GLfloat; typedef khronos_float_t GLclampf; typedef khronos_int32_t GLfixed; typedef khronos_int64_t GLint64; typedef khronos_uint64_t GLuint64; typedef khronos_int64_t GLint64EXT; typedef khronos_uint64_t GLuint64EXT; typedef khronos_intptr_t GLintptr; typedef khronos_ssize_t GLsizeiptr; typedef void ( *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); typedef unsigned short GLhalfNV; typedef GLintptr GLvdpauSurfaceNV; void glAccum GLenum op GLfloat value void glAccumxOES GLenum op GLfixed value void glActiveProgramEXT GLuint program void glActiveShaderProgram GLuint pipeline GLuint program void glActiveShaderProgramEXT GLuint pipeline GLuint program void glActiveStencilFaceEXT GLenum face void glActiveTexture GLenum texture void glActiveTextureARB GLenum texture void glActiveVaryingNV GLuint program const GLchar *name void glAlphaFragmentOp1ATI GLenum op GLuint dst GLuint dstMod GLuint arg1 GLuint arg1Rep GLuint arg1Mod void glAlphaFragmentOp2ATI GLenum op GLuint dst GLuint dstMod GLuint arg1 GLuint arg1Rep GLuint arg1Mod GLuint arg2 GLuint arg2Rep GLuint arg2Mod void glAlphaFragmentOp3ATI GLenum op GLuint dst GLuint dstMod GLuint arg1 GLuint arg1Rep GLuint arg1Mod GLuint arg2 GLuint arg2Rep GLuint arg2Mod GLuint arg3 GLuint arg3Rep GLuint arg3Mod void glAlphaFunc GLenum func GLfloat ref void glAlphaFuncQCOM GLenum func GLclampf ref void glAlphaFuncx GLenum func GLfixed ref void glAlphaFuncxOES GLenum func GLfixed ref void glApplyTextureEXT GLenum mode GLboolean glAreProgramsResidentNV GLsizei n const GLuint *programs GLboolean *residences GLboolean glAreTexturesResident GLsizei n const GLuint *textures GLboolean *residences GLboolean glAreTexturesResidentEXT GLsizei n const GLuint *textures GLboolean *residences void glArrayElement GLint i void glArrayElementEXT GLint i void glArrayObjectATI GLenum array GLint size GLenum type GLsizei stride GLuint buffer GLuint offset void glAsyncMarkerSGIX GLuint marker void glAttachObjectARB GLhandleARB containerObj GLhandleARB obj void glAttachShader GLuint program GLuint shader void glBegin GLenum mode void glBeginConditionalRender GLuint id GLenum mode void glBeginConditionalRenderNV GLuint id GLenum mode void glBeginConditionalRenderNVX GLuint id void glBeginFragmentShaderATI void glBeginOcclusionQueryNV GLuint id void glBeginPerfMonitorAMD GLuint monitor void glBeginPerfQueryINTEL GLuint queryHandle void glBeginQuery GLenum target GLuint id void glBeginQueryARB GLenum target GLuint id void glBeginQueryEXT GLenum target GLuint id void glBeginQueryIndexed GLenum target GLuint index GLuint id void glBeginTransformFeedback GLenum primitiveMode void glBeginTransformFeedbackEXT GLenum primitiveMode void glBeginTransformFeedbackNV GLenum primitiveMode void glBeginVertexShaderEXT void glBeginVideoCaptureNV GLuint video_capture_slot void glBindAttribLocation GLuint program GLuint index const GLchar *name void glBindAttribLocationARB GLhandleARB programObj GLuint index const GLcharARB *name void glBindBuffer GLenum target GLuint buffer void glBindBufferARB GLenum target GLuint buffer void glBindBufferBase GLenum target GLuint index GLuint buffer void glBindBufferBaseEXT GLenum target GLuint index GLuint buffer void glBindBufferBaseNV GLenum target GLuint index GLuint buffer void glBindBufferOffsetEXT GLenum target GLuint index GLuint buffer GLintptr offset void glBindBufferOffsetNV GLenum target GLuint index GLuint buffer GLintptr offset void glBindBufferRange GLenum target GLuint index GLuint buffer GLintptr offset GLsizeiptr size void glBindBufferRangeEXT GLenum target GLuint index GLuint buffer GLintptr offset GLsizeiptr size void glBindBufferRangeNV GLenum target GLuint index GLuint buffer GLintptr offset GLsizeiptr size void glBindBuffersBase GLenum target GLuint first GLsizei count const GLuint *buffers void glBindBuffersRange GLenum target GLuint first GLsizei count const GLuint *buffers const GLintptr *offsets const GLsizeiptr *sizes void glBindFragDataLocation GLuint program GLuint color const GLchar *name void glBindFragDataLocationEXT GLuint program GLuint color const GLchar *name void glBindFragDataLocationIndexed GLuint program GLuint colorNumber GLuint index const GLchar *name void glBindFragmentShaderATI GLuint id void glBindFramebuffer GLenum target GLuint framebuffer void glBindFramebufferEXT GLenum target GLuint framebuffer void glBindFramebufferOES GLenum target GLuint framebuffer void glBindImageTexture GLuint unit GLuint texture GLint level GLboolean layered GLint layer GLenum access GLenum format void glBindImageTextureEXT GLuint index GLuint texture GLint level GLboolean layered GLint layer GLenum access GLint format void glBindImageTextures GLuint first GLsizei count const GLuint *textures GLuint glBindLightParameterEXT GLenum light GLenum value GLuint glBindMaterialParameterEXT GLenum face GLenum value void glBindMultiTextureEXT GLenum texunit GLenum target GLuint texture GLuint glBindParameterEXT GLenum value void glBindProgramARB GLenum target GLuint program void glBindProgramNV GLenum target GLuint id void glBindProgramPipeline GLuint pipeline void glBindProgramPipelineEXT GLuint pipeline void glBindRenderbuffer GLenum target GLuint renderbuffer void glBindRenderbufferEXT GLenum target GLuint renderbuffer void glBindRenderbufferOES GLenum target GLuint renderbuffer void glBindSampler GLuint unit GLuint sampler void glBindSamplers GLuint first GLsizei count const GLuint *samplers GLuint glBindTexGenParameterEXT GLenum unit GLenum coord GLenum value void glBindTexture GLenum target GLuint texture void glBindTextureEXT GLenum target GLuint texture void glBindTextureUnit GLuint unit GLuint texture GLuint glBindTextureUnitParameterEXT GLenum unit GLenum value void glBindTextures GLuint first GLsizei count const GLuint *textures void glBindTransformFeedback GLenum target GLuint id void glBindTransformFeedbackNV GLenum target GLuint id void glBindVertexArray GLuint array void glBindVertexArrayAPPLE GLuint array void glBindVertexArrayOES GLuint array void glBindVertexBuffer GLuint bindingindex GLuint buffer GLintptr offset GLsizei stride void glBindVertexBuffers GLuint first GLsizei count const GLuint *buffers const GLintptr *offsets const GLsizei *strides void glBindVertexShaderEXT GLuint id void glBindVideoCaptureStreamBufferNV GLuint video_capture_slot GLuint stream GLenum frame_region GLintptrARB offset void glBindVideoCaptureStreamTextureNV GLuint video_capture_slot GLuint stream GLenum frame_region GLenum target GLuint texture void glBinormal3bEXT GLbyte bx GLbyte by GLbyte bz void glBinormal3bvEXT const GLbyte *v void glBinormal3dEXT GLdouble bx GLdouble by GLdouble bz void glBinormal3dvEXT const GLdouble *v void glBinormal3fEXT GLfloat bx GLfloat by GLfloat bz void glBinormal3fvEXT const GLfloat *v void glBinormal3iEXT GLint bx GLint by GLint bz void glBinormal3ivEXT const GLint *v void glBinormal3sEXT GLshort bx GLshort by GLshort bz void glBinormal3svEXT const GLshort *v void glBinormalPointerEXT GLenum type GLsizei stride const void *pointer void glBitmap GLsizei width GLsizei height GLfloat xorig GLfloat yorig GLfloat xmove GLfloat ymove const GLubyte *bitmap void glBitmapxOES GLsizei width GLsizei height GLfixed xorig GLfixed yorig GLfixed xmove GLfixed ymove const GLubyte *bitmap void glBlendBarrierKHR void glBlendBarrierNV void glBlendColor GLfloat red GLfloat green GLfloat blue GLfloat alpha void glBlendColorEXT GLfloat red GLfloat green GLfloat blue GLfloat alpha void glBlendColorxOES GLfixed red GLfixed green GLfixed blue GLfixed alpha void glBlendEquation GLenum mode void glBlendEquationEXT GLenum mode void glBlendEquationIndexedAMD GLuint buf GLenum mode void glBlendEquationOES GLenum mode void glBlendEquationSeparate GLenum modeRGB GLenum modeAlpha void glBlendEquationSeparateEXT GLenum modeRGB GLenum modeAlpha void glBlendEquationSeparateIndexedAMD GLuint buf GLenum modeRGB GLenum modeAlpha void glBlendEquationSeparateOES GLenum modeRGB GLenum modeAlpha void glBlendEquationSeparatei GLuint buf GLenum modeRGB GLenum modeAlpha void glBlendEquationSeparateiARB GLuint buf GLenum modeRGB GLenum modeAlpha void glBlendEquationSeparateiEXT GLuint buf GLenum modeRGB GLenum modeAlpha void glBlendEquationi GLuint buf GLenum mode void glBlendEquationiARB GLuint buf GLenum mode void glBlendEquationiEXT GLuint buf GLenum mode void glBlendFunc GLenum sfactor GLenum dfactor void glBlendFuncIndexedAMD GLuint buf GLenum src GLenum dst void glBlendFuncSeparate GLenum sfactorRGB GLenum dfactorRGB GLenum sfactorAlpha GLenum dfactorAlpha void glBlendFuncSeparateEXT GLenum sfactorRGB GLenum dfactorRGB GLenum sfactorAlpha GLenum dfactorAlpha void glBlendFuncSeparateINGR GLenum sfactorRGB GLenum dfactorRGB GLenum sfactorAlpha GLenum dfactorAlpha void glBlendFuncSeparateIndexedAMD GLuint buf GLenum srcRGB GLenum dstRGB GLenum srcAlpha GLenum dstAlpha void glBlendFuncSeparateOES GLenum srcRGB GLenum dstRGB GLenum srcAlpha GLenum dstAlpha void glBlendFuncSeparatei GLuint buf GLenum srcRGB GLenum dstRGB GLenum srcAlpha GLenum dstAlpha void glBlendFuncSeparateiARB GLuint buf GLenum srcRGB GLenum dstRGB GLenum srcAlpha GLenum dstAlpha void glBlendFuncSeparateiEXT GLuint buf GLenum srcRGB GLenum dstRGB GLenum srcAlpha GLenum dstAlpha void glBlendFunci GLuint buf GLenum src GLenum dst void glBlendFunciARB GLuint buf GLenum src GLenum dst void glBlendFunciEXT GLuint buf GLenum src GLenum dst void glBlendParameteriNV GLenum pname GLint value void glBlitFramebuffer GLint srcX0 GLint srcY0 GLint srcX1 GLint srcY1 GLint dstX0 GLint dstY0 GLint dstX1 GLint dstY1 GLbitfield mask GLenum filter void glBlitFramebufferANGLE GLint srcX0 GLint srcY0 GLint srcX1 GLint srcY1 GLint dstX0 GLint dstY0 GLint dstX1 GLint dstY1 GLbitfield mask GLenum filter void glBlitFramebufferEXT GLint srcX0 GLint srcY0 GLint srcX1 GLint srcY1 GLint dstX0 GLint dstY0 GLint dstX1 GLint dstY1 GLbitfield mask GLenum filter void glBlitFramebufferNV GLint srcX0 GLint srcY0 GLint srcX1 GLint srcY1 GLint dstX0 GLint dstY0 GLint dstX1 GLint dstY1 GLbitfield mask GLenum filter void glBlitNamedFramebuffer GLuint readFramebuffer GLuint drawFramebuffer GLint srcX0 GLint srcY0 GLint srcX1 GLint srcY1 GLint dstX0 GLint dstY0 GLint dstX1 GLint dstY1 GLbitfield mask GLenum filter void glBufferAddressRangeNV GLenum pname GLuint index GLuint64EXT address GLsizeiptr length void glBufferData GLenum target GLsizeiptr size const void *data GLenum usage void glBufferDataARB GLenum target GLsizeiptrARB size const void *data GLenum usage void glBufferPageCommitmentARB GLenum target GLintptr offset GLsizeiptr size GLboolean commit void glBufferParameteriAPPLE GLenum target GLenum pname GLint param void glBufferStorage GLenum target GLsizeiptr size const void *data GLbitfield flags void glBufferSubData GLenum target GLintptr offset GLsizeiptr size const void *data void glBufferSubDataARB GLenum target GLintptrARB offset GLsizeiptrARB size const void *data void glCallList GLuint list void glCallLists GLsizei n GLenum type const void *lists GLenum glCheckFramebufferStatus GLenum target GLenum glCheckFramebufferStatusEXT GLenum target GLenum glCheckFramebufferStatusOES GLenum target GLenum glCheckNamedFramebufferStatus GLuint framebuffer GLenum target GLenum glCheckNamedFramebufferStatusEXT GLuint framebuffer GLenum target void glClampColor GLenum target GLenum clamp void glClampColorARB GLenum target GLenum clamp void glClear GLbitfield mask void glClearAccum GLfloat red GLfloat green GLfloat blue GLfloat alpha void glClearAccumxOES GLfixed red GLfixed green GLfixed blue GLfixed alpha void glClearBufferData GLenum target GLenum internalformat GLenum format GLenum type const void *data void glClearBufferSubData GLenum target GLenum internalformat GLintptr offset GLsizeiptr size GLenum format GLenum type const void *data void glClearBufferfi GLenum buffer GLint drawbuffer GLfloat depth GLint stencil void glClearBufferfv GLenum buffer GLint drawbuffer const GLfloat *value void glClearBufferiv GLenum buffer GLint drawbuffer const GLint *value void glClearBufferuiv GLenum buffer GLint drawbuffer const GLuint *value void glClearColor GLfloat red GLfloat green GLfloat blue GLfloat alpha void glClearColorIiEXT GLint red GLint green GLint blue GLint alpha void glClearColorIuiEXT GLuint red GLuint green GLuint blue GLuint alpha void glClearColorx GLfixed red GLfixed green GLfixed blue GLfixed alpha void glClearColorxOES GLfixed red GLfixed green GLfixed blue GLfixed alpha void glClearDepth GLdouble depth void glClearDepthdNV GLdouble depth void glClearDepthf GLfloat d void glClearDepthfOES GLclampf depth void glClearDepthx GLfixed depth void glClearDepthxOES GLfixed depth void glClearIndex GLfloat c void glClearNamedBufferData GLuint buffer GLenum internalformat GLenum format GLenum type const void *data void glClearNamedBufferDataEXT GLuint buffer GLenum internalformat GLenum format GLenum type const void *data void glClearNamedBufferSubData GLuint buffer GLenum internalformat GLintptr offset GLsizei size GLenum format GLenum type const void *data void glClearNamedBufferSubDataEXT GLuint buffer GLenum internalformat GLsizeiptr offset GLsizeiptr size GLenum format GLenum type const void *data void glClearNamedFramebufferfi GLuint framebuffer GLenum buffer const GLfloat depth GLint stencil void glClearNamedFramebufferfv GLuint framebuffer GLenum buffer GLint drawbuffer const GLfloat *value void glClearNamedFramebufferiv GLuint framebuffer GLenum buffer GLint drawbuffer const GLint *value void glClearNamedFramebufferuiv GLuint framebuffer GLenum buffer GLint drawbuffer const GLuint *value void glClearStencil GLint s void glClearTexImage GLuint texture GLint level GLenum format GLenum type const void *data void glClearTexSubImage GLuint texture GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLenum type const void *data void glClientActiveTexture GLenum texture void glClientActiveTextureARB GLenum texture void glClientActiveVertexStreamATI GLenum stream void glClientAttribDefaultEXT GLbitfield mask GLenum glClientWaitSync GLsync sync GLbitfield flags GLuint64 timeout GLenum glClientWaitSyncAPPLE GLsync sync GLbitfield flags GLuint64 timeout void glClipControl GLenum origin GLenum depth void glClipPlane GLenum plane const GLdouble *equation void glClipPlanef GLenum p const GLfloat *eqn void glClipPlanefIMG GLenum p const GLfloat *eqn void glClipPlanefOES GLenum plane const GLfloat *equation void glClipPlanex GLenum plane const GLfixed *equation void glClipPlanexIMG GLenum p const GLfixed *eqn void glClipPlanexOES GLenum plane const GLfixed *equation void glColor3b GLbyte red GLbyte green GLbyte blue void glColor3bv const GLbyte *v void glColor3d GLdouble red GLdouble green GLdouble blue void glColor3dv const GLdouble *v void glColor3f GLfloat red GLfloat green GLfloat blue void glColor3fVertex3fSUN GLfloat r GLfloat g GLfloat b GLfloat x GLfloat y GLfloat z void glColor3fVertex3fvSUN const GLfloat *c const GLfloat *v void glColor3fv const GLfloat *v void glColor3hNV GLhalfNV red GLhalfNV green GLhalfNV blue void glColor3hvNV const GLhalfNV *v void glColor3i GLint red GLint green GLint blue void glColor3iv const GLint *v void glColor3s GLshort red GLshort green GLshort blue void glColor3sv const GLshort *v void glColor3ub GLubyte red GLubyte green GLubyte blue void glColor3ubv const GLubyte *v void glColor3ui GLuint red GLuint green GLuint blue void glColor3uiv const GLuint *v void glColor3us GLushort red GLushort green GLushort blue void glColor3usv const GLushort *v void glColor3xOES GLfixed red GLfixed green GLfixed blue void glColor3xvOES const GLfixed *components void glColor4b GLbyte red GLbyte green GLbyte blue GLbyte alpha void glColor4bv const GLbyte *v void glColor4d GLdouble red GLdouble green GLdouble blue GLdouble alpha void glColor4dv const GLdouble *v void glColor4f GLfloat red GLfloat green GLfloat blue GLfloat alpha void glColor4fNormal3fVertex3fSUN GLfloat r GLfloat g GLfloat b GLfloat a GLfloat nx GLfloat ny GLfloat nz GLfloat x GLfloat y GLfloat z void glColor4fNormal3fVertex3fvSUN const GLfloat *c const GLfloat *n const GLfloat *v void glColor4fv const GLfloat *v void glColor4hNV GLhalfNV red GLhalfNV green GLhalfNV blue GLhalfNV alpha void glColor4hvNV const GLhalfNV *v void glColor4i GLint red GLint green GLint blue GLint alpha void glColor4iv const GLint *v void glColor4s GLshort red GLshort green GLshort blue GLshort alpha void glColor4sv const GLshort *v void glColor4ub GLubyte red GLubyte green GLubyte blue GLubyte alpha void glColor4ubVertex2fSUN GLubyte r GLubyte g GLubyte b GLubyte a GLfloat x GLfloat y void glColor4ubVertex2fvSUN const GLubyte *c const GLfloat *v void glColor4ubVertex3fSUN GLubyte r GLubyte g GLubyte b GLubyte a GLfloat x GLfloat y GLfloat z void glColor4ubVertex3fvSUN const GLubyte *c const GLfloat *v void glColor4ubv const GLubyte *v void glColor4ui GLuint red GLuint green GLuint blue GLuint alpha void glColor4uiv const GLuint *v void glColor4us GLushort red GLushort green GLushort blue GLushort alpha void glColor4usv const GLushort *v void glColor4x GLfixed red GLfixed green GLfixed blue GLfixed alpha void glColor4xOES GLfixed red GLfixed green GLfixed blue GLfixed alpha void glColor4xvOES const GLfixed *components void glColorFormatNV GLint size GLenum type GLsizei stride void glColorFragmentOp1ATI GLenum op GLuint dst GLuint dstMask GLuint dstMod GLuint arg1 GLuint arg1Rep GLuint arg1Mod void glColorFragmentOp2ATI GLenum op GLuint dst GLuint dstMask GLuint dstMod GLuint arg1 GLuint arg1Rep GLuint arg1Mod GLuint arg2 GLuint arg2Rep GLuint arg2Mod void glColorFragmentOp3ATI GLenum op GLuint dst GLuint dstMask GLuint dstMod GLuint arg1 GLuint arg1Rep GLuint arg1Mod GLuint arg2 GLuint arg2Rep GLuint arg2Mod GLuint arg3 GLuint arg3Rep GLuint arg3Mod void glColorMask GLboolean red GLboolean green GLboolean blue GLboolean alpha void glColorMaskIndexedEXT GLuint index GLboolean r GLboolean g GLboolean b GLboolean a void glColorMaski GLuint index GLboolean r GLboolean g GLboolean b GLboolean a void glColorMaskiEXT GLuint index GLboolean r GLboolean g GLboolean b GLboolean a void glColorMaterial GLenum face GLenum mode void glColorP3ui GLenum type GLuint color void glColorP3uiv GLenum type const GLuint *color void glColorP4ui GLenum type GLuint color void glColorP4uiv GLenum type const GLuint *color void glColorPointer GLint size GLenum type GLsizei stride const void *pointer void glColorPointerEXT GLint size GLenum type GLsizei stride GLsizei count const void *pointer void glColorPointerListIBM GLint size GLenum type GLint stride const void **pointer GLint ptrstride void glColorPointervINTEL GLint size GLenum type const void **pointer void glColorSubTable GLenum target GLsizei start GLsizei count GLenum format GLenum type const void *data void glColorSubTableEXT GLenum target GLsizei start GLsizei count GLenum format GLenum type const void *data void glColorTable GLenum target GLenum internalformat GLsizei width GLenum format GLenum type const void *table void glColorTableEXT GLenum target GLenum internalFormat GLsizei width GLenum format GLenum type const void *table void glColorTableParameterfv GLenum target GLenum pname const GLfloat *params void glColorTableParameterfvSGI GLenum target GLenum pname const GLfloat *params void glColorTableParameteriv GLenum target GLenum pname const GLint *params void glColorTableParameterivSGI GLenum target GLenum pname const GLint *params void glColorTableSGI GLenum target GLenum internalformat GLsizei width GLenum format GLenum type const void *table void glCombinerInputNV GLenum stage GLenum portion GLenum variable GLenum input GLenum mapping GLenum componentUsage void glCombinerOutputNV GLenum stage GLenum portion GLenum abOutput GLenum cdOutput GLenum sumOutput GLenum scale GLenum bias GLboolean abDotProduct GLboolean cdDotProduct GLboolean muxSum void glCombinerParameterfNV GLenum pname GLfloat param void glCombinerParameterfvNV GLenum pname const GLfloat *params void glCombinerParameteriNV GLenum pname GLint param void glCombinerParameterivNV GLenum pname const GLint *params void glCombinerStageParameterfvNV GLenum stage GLenum pname const GLfloat *params void glCompileShader GLuint shader void glCompileShaderARB GLhandleARB shaderObj void glCompileShaderIncludeARB GLuint shader GLsizei count const GLchar *const*path const GLint *length void glCompressedMultiTexImage1DEXT GLenum texunit GLenum target GLint level GLenum internalformat GLsizei width GLint border GLsizei imageSize const void *bits void glCompressedMultiTexImage2DEXT GLenum texunit GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLint border GLsizei imageSize const void *bits void glCompressedMultiTexImage3DEXT GLenum texunit GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLsizei depth GLint border GLsizei imageSize const void *bits void glCompressedMultiTexSubImage1DEXT GLenum texunit GLenum target GLint level GLint xoffset GLsizei width GLenum format GLsizei imageSize const void *bits void glCompressedMultiTexSubImage2DEXT GLenum texunit GLenum target GLint level GLint xoffset GLint yoffset GLsizei width GLsizei height GLenum format GLsizei imageSize const void *bits void glCompressedMultiTexSubImage3DEXT GLenum texunit GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLsizei imageSize const void *bits void glCompressedTexImage1D GLenum target GLint level GLenum internalformat GLsizei width GLint border GLsizei imageSize const void *data void glCompressedTexImage1DARB GLenum target GLint level GLenum internalformat GLsizei width GLint border GLsizei imageSize const void *data void glCompressedTexImage2D GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLint border GLsizei imageSize const void *data void glCompressedTexImage2DARB GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLint border GLsizei imageSize const void *data void glCompressedTexImage3D GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLsizei depth GLint border GLsizei imageSize const void *data void glCompressedTexImage3DARB GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLsizei depth GLint border GLsizei imageSize const void *data void glCompressedTexImage3DOES GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLsizei depth GLint border GLsizei imageSize const void *data void glCompressedTexSubImage1D GLenum target GLint level GLint xoffset GLsizei width GLenum format GLsizei imageSize const void *data void glCompressedTexSubImage1DARB GLenum target GLint level GLint xoffset GLsizei width GLenum format GLsizei imageSize const void *data void glCompressedTexSubImage2D GLenum target GLint level GLint xoffset GLint yoffset GLsizei width GLsizei height GLenum format GLsizei imageSize const void *data void glCompressedTexSubImage2DARB GLenum target GLint level GLint xoffset GLint yoffset GLsizei width GLsizei height GLenum format GLsizei imageSize const void *data void glCompressedTexSubImage3D GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLsizei imageSize const void *data void glCompressedTexSubImage3DARB GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLsizei imageSize const void *data void glCompressedTexSubImage3DOES GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLsizei imageSize const void *data void glCompressedTextureImage1DEXT GLuint texture GLenum target GLint level GLenum internalformat GLsizei width GLint border GLsizei imageSize const void *bits void glCompressedTextureImage2DEXT GLuint texture GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLint border GLsizei imageSize const void *bits void glCompressedTextureImage3DEXT GLuint texture GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLsizei depth GLint border GLsizei imageSize const void *bits void glCompressedTextureSubImage1D GLuint texture GLint level GLint xoffset GLsizei width GLenum format GLsizei imageSize const void *data void glCompressedTextureSubImage1DEXT GLuint texture GLenum target GLint level GLint xoffset GLsizei width GLenum format GLsizei imageSize const void *bits void glCompressedTextureSubImage2D GLuint texture GLint level GLint xoffset GLint yoffset GLsizei width GLsizei height GLenum format GLsizei imageSize const void *data void glCompressedTextureSubImage2DEXT GLuint texture GLenum target GLint level GLint xoffset GLint yoffset GLsizei width GLsizei height GLenum format GLsizei imageSize const void *bits void glCompressedTextureSubImage3D GLuint texture GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLsizei imageSize const void *data void glCompressedTextureSubImage3DEXT GLuint texture GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLsizei imageSize const void *bits void glConvolutionFilter1D GLenum target GLenum internalformat GLsizei width GLenum format GLenum type const void *image void glConvolutionFilter1DEXT GLenum target GLenum internalformat GLsizei width GLenum format GLenum type const void *image void glConvolutionFilter2D GLenum target GLenum internalformat GLsizei width GLsizei height GLenum format GLenum type const void *image void glConvolutionFilter2DEXT GLenum target GLenum internalformat GLsizei width GLsizei height GLenum format GLenum type const void *image void glConvolutionParameterf GLenum target GLenum pname GLfloat params void glConvolutionParameterfEXT GLenum target GLenum pname GLfloat params void glConvolutionParameterfv GLenum target GLenum pname const GLfloat *params void glConvolutionParameterfvEXT GLenum target GLenum pname const GLfloat *params void glConvolutionParameteri GLenum target GLenum pname GLint params void glConvolutionParameteriEXT GLenum target GLenum pname GLint params void glConvolutionParameteriv GLenum target GLenum pname const GLint *params void glConvolutionParameterivEXT GLenum target GLenum pname const GLint *params void glConvolutionParameterxOES GLenum target GLenum pname GLfixed param void glConvolutionParameterxvOES GLenum target GLenum pname const GLfixed *params void glCopyBufferSubData GLenum readTarget GLenum writeTarget GLintptr readOffset GLintptr writeOffset GLsizeiptr size void glCopyBufferSubDataNV GLenum readTarget GLenum writeTarget GLintptr readOffset GLintptr writeOffset GLsizeiptr size void glCopyColorSubTable GLenum target GLsizei start GLint x GLint y GLsizei width void glCopyColorSubTableEXT GLenum target GLsizei start GLint x GLint y GLsizei width void glCopyColorTable GLenum target GLenum internalformat GLint x GLint y GLsizei width void glCopyColorTableSGI GLenum target GLenum internalformat GLint x GLint y GLsizei width void glCopyConvolutionFilter1D GLenum target GLenum internalformat GLint x GLint y GLsizei width void glCopyConvolutionFilter1DEXT GLenum target GLenum internalformat GLint x GLint y GLsizei width void glCopyConvolutionFilter2D GLenum target GLenum internalformat GLint x GLint y GLsizei width GLsizei height void glCopyConvolutionFilter2DEXT GLenum target GLenum internalformat GLint x GLint y GLsizei width GLsizei height void glCopyImageSubData GLuint srcName GLenum srcTarget GLint srcLevel GLint srcX GLint srcY GLint srcZ GLuint dstName GLenum dstTarget GLint dstLevel GLint dstX GLint dstY GLint dstZ GLsizei srcWidth GLsizei srcHeight GLsizei srcDepth void glCopyImageSubDataEXT GLuint srcName GLenum srcTarget GLint srcLevel GLint srcX GLint srcY GLint srcZ GLuint dstName GLenum dstTarget GLint dstLevel GLint dstX GLint dstY GLint dstZ GLsizei srcWidth GLsizei srcHeight GLsizei srcDepth void glCopyImageSubDataNV GLuint srcName GLenum srcTarget GLint srcLevel GLint srcX GLint srcY GLint srcZ GLuint dstName GLenum dstTarget GLint dstLevel GLint dstX GLint dstY GLint dstZ GLsizei width GLsizei height GLsizei depth void glCopyMultiTexImage1DEXT GLenum texunit GLenum target GLint level GLenum internalformat GLint x GLint y GLsizei width GLint border void glCopyMultiTexImage2DEXT GLenum texunit GLenum target GLint level GLenum internalformat GLint x GLint y GLsizei width GLsizei height GLint border void glCopyMultiTexSubImage1DEXT GLenum texunit GLenum target GLint level GLint xoffset GLint x GLint y GLsizei width void glCopyMultiTexSubImage2DEXT GLenum texunit GLenum target GLint level GLint xoffset GLint yoffset GLint x GLint y GLsizei width GLsizei height void glCopyMultiTexSubImage3DEXT GLenum texunit GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLint x GLint y GLsizei width GLsizei height void glCopyNamedBufferSubData GLuint readBuffer GLuint writeBuffer GLintptr readOffset GLintptr writeOffset GLsizei size void glCopyPathNV GLuint resultPath GLuint srcPath void glCopyPixels GLint x GLint y GLsizei width GLsizei height GLenum type void glCopyTexImage1D GLenum target GLint level GLenum internalformat GLint x GLint y GLsizei width GLint border void glCopyTexImage1DEXT GLenum target GLint level GLenum internalformat GLint x GLint y GLsizei width GLint border void glCopyTexImage2D GLenum target GLint level GLenum internalformat GLint x GLint y GLsizei width GLsizei height GLint border void glCopyTexImage2DEXT GLenum target GLint level GLenum internalformat GLint x GLint y GLsizei width GLsizei height GLint border void glCopyTexSubImage1D GLenum target GLint level GLint xoffset GLint x GLint y GLsizei width void glCopyTexSubImage1DEXT GLenum target GLint level GLint xoffset GLint x GLint y GLsizei width void glCopyTexSubImage2D GLenum target GLint level GLint xoffset GLint yoffset GLint x GLint y GLsizei width GLsizei height void glCopyTexSubImage2DEXT GLenum target GLint level GLint xoffset GLint yoffset GLint x GLint y GLsizei width GLsizei height void glCopyTexSubImage3D GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLint x GLint y GLsizei width GLsizei height void glCopyTexSubImage3DEXT GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLint x GLint y GLsizei width GLsizei height void glCopyTexSubImage3DOES GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLint x GLint y GLsizei width GLsizei height void glCopyTextureImage1DEXT GLuint texture GLenum target GLint level GLenum internalformat GLint x GLint y GLsizei width GLint border void glCopyTextureImage2DEXT GLuint texture GLenum target GLint level GLenum internalformat GLint x GLint y GLsizei width GLsizei height GLint border void glCopyTextureLevelsAPPLE GLuint destinationTexture GLuint sourceTexture GLint sourceBaseLevel GLsizei sourceLevelCount void glCopyTextureSubImage1D GLuint texture GLint level GLint xoffset GLint x GLint y GLsizei width void glCopyTextureSubImage1DEXT GLuint texture GLenum target GLint level GLint xoffset GLint x GLint y GLsizei width void glCopyTextureSubImage2D GLuint texture GLint level GLint xoffset GLint yoffset GLint x GLint y GLsizei width GLsizei height void glCopyTextureSubImage2DEXT GLuint texture GLenum target GLint level GLint xoffset GLint yoffset GLint x GLint y GLsizei width GLsizei height void glCopyTextureSubImage3D GLuint texture GLint level GLint xoffset GLint yoffset GLint zoffset GLint x GLint y GLsizei width GLsizei height void glCopyTextureSubImage3DEXT GLuint texture GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLint x GLint y GLsizei width GLsizei height void glCoverFillPathInstancedNV GLsizei numPaths GLenum pathNameType const void *paths GLuint pathBase GLenum coverMode GLenum transformType const GLfloat *transformValues void glCoverFillPathNV GLuint path GLenum coverMode void glCoverStrokePathInstancedNV GLsizei numPaths GLenum pathNameType const void *paths GLuint pathBase GLenum coverMode GLenum transformType const GLfloat *transformValues void glCoverStrokePathNV GLuint path GLenum coverMode void glCoverageMaskNV GLboolean mask void glCoverageOperationNV GLenum operation void glCreateBuffers GLsizei n GLuint *buffers void glCreateFramebuffers GLsizei n GLuint *framebuffers void glCreatePerfQueryINTEL GLuint queryId GLuint *queryHandle GLuint glCreateProgram GLhandleARB glCreateProgramObjectARB void glCreateProgramPipelines GLsizei n GLuint *pipelines void glCreateQueries GLenum target GLsizei n GLuint *ids void glCreateRenderbuffers GLsizei n GLuint *renderbuffers void glCreateSamplers GLsizei n GLuint *samplers GLuint glCreateShader GLenum type GLhandleARB glCreateShaderObjectARB GLenum shaderType GLuint glCreateShaderProgramEXT GLenum type const GLchar *string GLuint glCreateShaderProgramv GLenum type GLsizei count const GLchar *const*strings GLuint glCreateShaderProgramvEXT GLenum type GLsizei count const GLchar **strings GLsync glCreateSyncFromCLeventARB struct _cl_context *context struct _cl_event *event GLbitfield flags void glCreateTextures GLenum target GLsizei n GLuint *textures void glCreateTransformFeedbacks GLsizei n GLuint *ids void glCreateVertexArrays GLsizei n GLuint *arrays void glCullFace GLenum mode void glCullParameterdvEXT GLenum pname GLdouble *params void glCullParameterfvEXT GLenum pname GLfloat *params void glCurrentPaletteMatrixARB GLint index void glCurrentPaletteMatrixOES GLuint matrixpaletteindex void glDebugMessageCallback GLDEBUGPROC callback const void *userParam void glDebugMessageCallbackAMD GLDEBUGPROCAMD callback void *userParam void glDebugMessageCallbackARB GLDEBUGPROCARB callback const void *userParam void glDebugMessageCallbackKHR GLDEBUGPROCKHR callback const void *userParam void glDebugMessageControl GLenum source GLenum type GLenum severity GLsizei count const GLuint *ids GLboolean enabled void glDebugMessageControlARB GLenum source GLenum type GLenum severity GLsizei count const GLuint *ids GLboolean enabled void glDebugMessageControlKHR GLenum source GLenum type GLenum severity GLsizei count const GLuint *ids GLboolean enabled void glDebugMessageEnableAMD GLenum category GLenum severity GLsizei count const GLuint *ids GLboolean enabled void glDebugMessageInsert GLenum source GLenum type GLuint id GLenum severity GLsizei length const GLchar *buf void glDebugMessageInsertAMD GLenum category GLenum severity GLuint id GLsizei length const GLchar *buf void glDebugMessageInsertARB GLenum source GLenum type GLuint id GLenum severity GLsizei length const GLchar *buf void glDebugMessageInsertKHR GLenum source GLenum type GLuint id GLenum severity GLsizei length const GLchar *buf void glDeformSGIX GLbitfield mask void glDeformationMap3dSGIX GLenum target GLdouble u1 GLdouble u2 GLint ustride GLint uorder GLdouble v1 GLdouble v2 GLint vstride GLint vorder GLdouble w1 GLdouble w2 GLint wstride GLint worder const GLdouble *points void glDeformationMap3fSGIX GLenum target GLfloat u1 GLfloat u2 GLint ustride GLint uorder GLfloat v1 GLfloat v2 GLint vstride GLint vorder GLfloat w1 GLfloat w2 GLint wstride GLint worder const GLfloat *points void glDeleteAsyncMarkersSGIX GLuint marker GLsizei range void glDeleteBuffers GLsizei n const GLuint *buffers void glDeleteBuffersARB GLsizei n const GLuint *buffers void glDeleteFencesAPPLE GLsizei n const GLuint *fences void glDeleteFencesNV GLsizei n const GLuint *fences void glDeleteFragmentShaderATI GLuint id void glDeleteFramebuffers GLsizei n const GLuint *framebuffers void glDeleteFramebuffersEXT GLsizei n const GLuint *framebuffers void glDeleteFramebuffersOES GLsizei n const GLuint *framebuffers void glDeleteLists GLuint list GLsizei range void glDeleteNamedStringARB GLint namelen const GLchar *name void glDeleteNamesAMD GLenum identifier GLuint num const GLuint *names void glDeleteObjectARB GLhandleARB obj void glDeleteOcclusionQueriesNV GLsizei n const GLuint *ids void glDeletePathsNV GLuint path GLsizei range void glDeletePerfMonitorsAMD GLsizei n GLuint *monitors void glDeletePerfQueryINTEL GLuint queryHandle void glDeleteProgram GLuint program void glDeleteProgramPipelines GLsizei n const GLuint *pipelines void glDeleteProgramPipelinesEXT GLsizei n const GLuint *pipelines void glDeleteProgramsARB GLsizei n const GLuint *programs void glDeleteProgramsNV GLsizei n const GLuint *programs void glDeleteQueries GLsizei n const GLuint *ids void glDeleteQueriesARB GLsizei n const GLuint *ids void glDeleteQueriesEXT GLsizei n const GLuint *ids void glDeleteRenderbuffers GLsizei n const GLuint *renderbuffers void glDeleteRenderbuffersEXT GLsizei n const GLuint *renderbuffers void glDeleteRenderbuffersOES GLsizei n const GLuint *renderbuffers void glDeleteSamplers GLsizei count const GLuint *samplers void glDeleteShader GLuint shader void glDeleteSync GLsync sync void glDeleteSyncAPPLE GLsync sync void glDeleteTextures GLsizei n const GLuint *textures void glDeleteTexturesEXT GLsizei n const GLuint *textures void glDeleteTransformFeedbacks GLsizei n const GLuint *ids void glDeleteTransformFeedbacksNV GLsizei n const GLuint *ids void glDeleteVertexArrays GLsizei n const GLuint *arrays void glDeleteVertexArraysAPPLE GLsizei n const GLuint *arrays void glDeleteVertexArraysOES GLsizei n const GLuint *arrays void glDeleteVertexShaderEXT GLuint id void glDepthBoundsEXT GLclampd zmin GLclampd zmax void glDepthBoundsdNV GLdouble zmin GLdouble zmax void glDepthFunc GLenum func void glDepthMask GLboolean flag void glDepthRange GLdouble near GLdouble far void glDepthRangeArrayv GLuint first GLsizei count const GLdouble *v void glDepthRangeArrayfvNV GLuint first GLsizei count const GLfloat *v void glDepthRangeIndexed GLuint index GLdouble n GLdouble f void glDepthRangeIndexedfNV GLuint index GLfloat n GLfloat f void glDepthRangedNV GLdouble zNear GLdouble zFar void glDepthRangef GLfloat n GLfloat f void glDepthRangefOES GLclampf n GLclampf f void glDepthRangex GLfixed n GLfixed f void glDepthRangexOES GLfixed n GLfixed f void glDetachObjectARB GLhandleARB containerObj GLhandleARB attachedObj void glDetachShader GLuint program GLuint shader void glDetailTexFuncSGIS GLenum target GLsizei n const GLfloat *points void glDisable GLenum cap void glDisableClientState GLenum array void glDisableClientStateIndexedEXT GLenum array GLuint index void glDisableClientStateiEXT GLenum array GLuint index void glDisableDriverControlQCOM GLuint driverControl void glDisableIndexedEXT GLenum target GLuint index void glDisableVariantClientStateEXT GLuint id void glDisableVertexArrayAttrib GLuint vaobj GLuint index void glDisableVertexArrayAttribEXT GLuint vaobj GLuint index void glDisableVertexArrayEXT GLuint vaobj GLenum array void glDisableVertexAttribAPPLE GLuint index GLenum pname void glDisableVertexAttribArray GLuint index void glDisableVertexAttribArrayARB GLuint index void glDisablei GLenum target GLuint index void glDisableiEXT GLenum target GLuint index void glDisableiNV GLenum target GLuint index void glDiscardFramebufferEXT GLenum target GLsizei numAttachments const GLenum *attachments void glDispatchCompute GLuint num_groups_x GLuint num_groups_y GLuint num_groups_z void glDispatchComputeGroupSizeARB GLuint num_groups_x GLuint num_groups_y GLuint num_groups_z GLuint group_size_x GLuint group_size_y GLuint group_size_z void glDispatchComputeIndirect GLintptr indirect void glDrawArrays GLenum mode GLint first GLsizei count void glDrawArraysEXT GLenum mode GLint first GLsizei count void glDrawArraysIndirect GLenum mode const void *indirect void glDrawArraysInstanced GLenum mode GLint first GLsizei count GLsizei instancecount void glDrawArraysInstancedANGLE GLenum mode GLint first GLsizei count GLsizei primcount void glDrawArraysInstancedARB GLenum mode GLint first GLsizei count GLsizei primcount void glDrawArraysInstancedBaseInstance GLenum mode GLint first GLsizei count GLsizei instancecount GLuint baseinstance void glDrawArraysInstancedBaseInstanceEXT GLenum mode GLint first GLsizei count GLsizei instancecount GLuint baseinstance void glDrawArraysInstancedEXT GLenum mode GLint start GLsizei count GLsizei primcount void glDrawArraysInstancedNV GLenum mode GLint first GLsizei count GLsizei primcount void glDrawBuffer GLenum buf void glDrawBuffers GLsizei n const GLenum *bufs void glDrawBuffersARB GLsizei n const GLenum *bufs void glDrawBuffersATI GLsizei n const GLenum *bufs void glDrawBuffersEXT GLsizei n const GLenum *bufs void glDrawBuffersIndexedEXT GLint n const GLenum *location const GLint *indices void glDrawBuffersNV GLsizei n const GLenum *bufs void glDrawElementArrayAPPLE GLenum mode GLint first GLsizei count void glDrawElementArrayATI GLenum mode GLsizei count void glDrawElements GLenum mode GLsizei count GLenum type const void *indices void glDrawElementsBaseVertex GLenum mode GLsizei count GLenum type const void *indices GLint basevertex void glDrawElementsBaseVertexEXT GLenum mode GLsizei count GLenum type const void *indices GLint basevertex void glDrawElementsIndirect GLenum mode GLenum type const void *indirect void glDrawElementsInstanced GLenum mode GLsizei count GLenum type const void *indices GLsizei instancecount void glDrawElementsInstancedANGLE GLenum mode GLsizei count GLenum type const void *indices GLsizei primcount void glDrawElementsInstancedARB GLenum mode GLsizei count GLenum type const void *indices GLsizei primcount void glDrawElementsInstancedBaseInstance GLenum mode GLsizei count GLenum type const void *indices GLsizei instancecount GLuint baseinstance void glDrawElementsInstancedBaseInstanceEXT GLenum mode GLsizei count GLenum type const void *indices GLsizei instancecount GLuint baseinstance void glDrawElementsInstancedBaseVertex GLenum mode GLsizei count GLenum type const void *indices GLsizei instancecount GLint basevertex void glDrawElementsInstancedBaseVertexEXT GLenum mode GLsizei count GLenum type const void *indices GLsizei instancecount GLint basevertex void glDrawElementsInstancedBaseVertexBaseInstance GLenum mode GLsizei count GLenum type const void *indices GLsizei instancecount GLint basevertex GLuint baseinstance void glDrawElementsInstancedBaseVertexBaseInstanceEXT GLenum mode GLsizei count GLenum type const void *indices GLsizei instancecount GLint basevertex GLuint baseinstance void glDrawElementsInstancedEXT GLenum mode GLsizei count GLenum type const void *indices GLsizei primcount void glDrawElementsInstancedNV GLenum mode GLsizei count GLenum type const void *indices GLsizei primcount void glDrawMeshArraysSUN GLenum mode GLint first GLsizei count GLsizei width void glDrawPixels GLsizei width GLsizei height GLenum format GLenum type const void *pixels void glDrawRangeElementArrayAPPLE GLenum mode GLuint start GLuint end GLint first GLsizei count void glDrawRangeElementArrayATI GLenum mode GLuint start GLuint end GLsizei count void glDrawRangeElements GLenum mode GLuint start GLuint end GLsizei count GLenum type const void *indices void glDrawRangeElementsBaseVertex GLenum mode GLuint start GLuint end GLsizei count GLenum type const void *indices GLint basevertex void glDrawRangeElementsBaseVertexEXT GLenum mode GLuint start GLuint end GLsizei count GLenum type const void *indices GLint basevertex void glDrawRangeElementsEXT GLenum mode GLuint start GLuint end GLsizei count GLenum type const void *indices void glDrawTexfOES GLfloat x GLfloat y GLfloat z GLfloat width GLfloat height void glDrawTexfvOES const GLfloat *coords void glDrawTexiOES GLint x GLint y GLint z GLint width GLint height void glDrawTexivOES const GLint *coords void glDrawTexsOES GLshort x GLshort y GLshort z GLshort width GLshort height void glDrawTexsvOES const GLshort *coords void glDrawTextureNV GLuint texture GLuint sampler GLfloat x0 GLfloat y0 GLfloat x1 GLfloat y1 GLfloat z GLfloat s0 GLfloat t0 GLfloat s1 GLfloat t1 void glDrawTexxOES GLfixed x GLfixed y GLfixed z GLfixed width GLfixed height void glDrawTexxvOES const GLfixed *coords void glDrawTransformFeedback GLenum mode GLuint id void glDrawTransformFeedbackInstanced GLenum mode GLuint id GLsizei instancecount void glDrawTransformFeedbackNV GLenum mode GLuint id void glDrawTransformFeedbackStream GLenum mode GLuint id GLuint stream void glDrawTransformFeedbackStreamInstanced GLenum mode GLuint id GLuint stream GLsizei instancecount void glEGLImageTargetRenderbufferStorageOES GLenum target GLeglImageOES image void glEGLImageTargetTexture2DOES GLenum target GLeglImageOES image void glEdgeFlag GLboolean flag void glEdgeFlagFormatNV GLsizei stride void glEdgeFlagPointer GLsizei stride const void *pointer void glEdgeFlagPointerEXT GLsizei stride GLsizei count const GLboolean *pointer void glEdgeFlagPointerListIBM GLint stride const GLboolean **pointer GLint ptrstride void glEdgeFlagv const GLboolean *flag void glElementPointerAPPLE GLenum type const void *pointer void glElementPointerATI GLenum type const void *pointer void glEnable GLenum cap void glEnableClientState GLenum array void glEnableClientStateIndexedEXT GLenum array GLuint index void glEnableClientStateiEXT GLenum array GLuint index void glEnableDriverControlQCOM GLuint driverControl void glEnableIndexedEXT GLenum target GLuint index void glEnableVariantClientStateEXT GLuint id void glEnableVertexArrayAttrib GLuint vaobj GLuint index void glEnableVertexArrayAttribEXT GLuint vaobj GLuint index void glEnableVertexArrayEXT GLuint vaobj GLenum array void glEnableVertexAttribAPPLE GLuint index GLenum pname void glEnableVertexAttribArray GLuint index void glEnableVertexAttribArrayARB GLuint index void glEnablei GLenum target GLuint index void glEnableiNV GLenum target GLuint index void glEnableiEXT GLenum target GLuint index void glEnd void glEndConditionalRender void glEndConditionalRenderNV void glEndConditionalRenderNVX void glEndFragmentShaderATI void glEndList void glEndOcclusionQueryNV void glEndPerfMonitorAMD GLuint monitor void glEndPerfQueryINTEL GLuint queryHandle void glEndQuery GLenum target void glEndQueryARB GLenum target void glEndQueryEXT GLenum target void glEndQueryIndexed GLenum target GLuint index void glEndTilingQCOM GLbitfield preserveMask void glEndTransformFeedback void glEndTransformFeedbackEXT void glEndTransformFeedbackNV void glEndVertexShaderEXT void glEndVideoCaptureNV GLuint video_capture_slot void glEvalCoord1d GLdouble u void glEvalCoord1dv const GLdouble *u void glEvalCoord1f GLfloat u void glEvalCoord1fv const GLfloat *u void glEvalCoord1xOES GLfixed u void glEvalCoord1xvOES const GLfixed *coords void glEvalCoord2d GLdouble u GLdouble v void glEvalCoord2dv const GLdouble *u void glEvalCoord2f GLfloat u GLfloat v void glEvalCoord2fv const GLfloat *u void glEvalCoord2xOES GLfixed u GLfixed v void glEvalCoord2xvOES const GLfixed *coords void glEvalMapsNV GLenum target GLenum mode void glEvalMesh1 GLenum mode GLint i1 GLint i2 void glEvalMesh2 GLenum mode GLint i1 GLint i2 GLint j1 GLint j2 void glEvalPoint1 GLint i void glEvalPoint2 GLint i GLint j void glExecuteProgramNV GLenum target GLuint id const GLfloat *params void glExtGetBufferPointervQCOM GLenum target void **params void glExtGetBuffersQCOM GLuint *buffers GLint maxBuffers GLint *numBuffers void glExtGetFramebuffersQCOM GLuint *framebuffers GLint maxFramebuffers GLint *numFramebuffers void glExtGetProgramBinarySourceQCOM GLuint program GLenum shadertype GLchar *source GLint *length void glExtGetProgramsQCOM GLuint *programs GLint maxPrograms GLint *numPrograms void glExtGetRenderbuffersQCOM GLuint *renderbuffers GLint maxRenderbuffers GLint *numRenderbuffers void glExtGetShadersQCOM GLuint *shaders GLint maxShaders GLint *numShaders void glExtGetTexLevelParameterivQCOM GLuint texture GLenum face GLint level GLenum pname GLint *params void glExtGetTexSubImageQCOM GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLenum type void *texels void glExtGetTexturesQCOM GLuint *textures GLint maxTextures GLint *numTextures GLboolean glExtIsProgramBinaryQCOM GLuint program void glExtTexObjectStateOverrideiQCOM GLenum target GLenum pname GLint param void glExtractComponentEXT GLuint res GLuint src GLuint num void glFeedbackBuffer GLsizei size GLenum type GLfloat *buffer void glFeedbackBufferxOES GLsizei n GLenum type const GLfixed *buffer GLsync glFenceSync GLenum condition GLbitfield flags GLsync glFenceSyncAPPLE GLenum condition GLbitfield flags void glFinalCombinerInputNV GLenum variable GLenum input GLenum mapping GLenum componentUsage void glFinish GLint glFinishAsyncSGIX GLuint *markerp void glFinishFenceAPPLE GLuint fence void glFinishFenceNV GLuint fence void glFinishObjectAPPLE GLenum object GLint name void glFinishTextureSUNX void glFlush void glFlushMappedBufferRange GLenum target GLintptr offset GLsizeiptr length void glFlushMappedBufferRangeAPPLE GLenum target GLintptr offset GLsizeiptr size void glFlushMappedBufferRangeEXT GLenum target GLintptr offset GLsizeiptr length void glFlushMappedNamedBufferRange GLuint buffer GLintptr offset GLsizei length void glFlushMappedNamedBufferRangeEXT GLuint buffer GLintptr offset GLsizeiptr length void glFlushPixelDataRangeNV GLenum target void glFlushRasterSGIX void glFlushStaticDataIBM GLenum target void glFlushVertexArrayRangeAPPLE GLsizei length void *pointer void glFlushVertexArrayRangeNV void glFogCoordFormatNV GLenum type GLsizei stride void glFogCoordPointer GLenum type GLsizei stride const void *pointer void glFogCoordPointerEXT GLenum type GLsizei stride const void *pointer void glFogCoordPointerListIBM GLenum type GLint stride const void **pointer GLint ptrstride void glFogCoordd GLdouble coord void glFogCoorddEXT GLdouble coord void glFogCoorddv const GLdouble *coord void glFogCoorddvEXT const GLdouble *coord void glFogCoordf GLfloat coord void glFogCoordfEXT GLfloat coord void glFogCoordfv const GLfloat *coord void glFogCoordfvEXT const GLfloat *coord void glFogCoordhNV GLhalfNV fog void glFogCoordhvNV const GLhalfNV *fog void glFogFuncSGIS GLsizei n const GLfloat *points void glFogf GLenum pname GLfloat param void glFogfv GLenum pname const GLfloat *params void glFogi GLenum pname GLint param void glFogiv GLenum pname const GLint *params void glFogx GLenum pname GLfixed param void glFogxOES GLenum pname GLfixed param void glFogxv GLenum pname const GLfixed *param void glFogxvOES GLenum pname const GLfixed *param void glFragmentColorMaterialSGIX GLenum face GLenum mode void glFragmentLightModelfSGIX GLenum pname GLfloat param void glFragmentLightModelfvSGIX GLenum pname const GLfloat *params void glFragmentLightModeliSGIX GLenum pname GLint param void glFragmentLightModelivSGIX GLenum pname const GLint *params void glFragmentLightfSGIX GLenum light GLenum pname GLfloat param void glFragmentLightfvSGIX GLenum light GLenum pname const GLfloat *params void glFragmentLightiSGIX GLenum light GLenum pname GLint param void glFragmentLightivSGIX GLenum light GLenum pname const GLint *params void glFragmentMaterialfSGIX GLenum face GLenum pname GLfloat param void glFragmentMaterialfvSGIX GLenum face GLenum pname const GLfloat *params void glFragmentMaterialiSGIX GLenum face GLenum pname GLint param void glFragmentMaterialivSGIX GLenum face GLenum pname const GLint *params void glFrameTerminatorGREMEDY void glFrameZoomSGIX GLint factor void glFramebufferDrawBufferEXT GLuint framebuffer GLenum mode void glFramebufferDrawBuffersEXT GLuint framebuffer GLsizei n const GLenum *bufs void glFramebufferParameteri GLenum target GLenum pname GLint param void glFramebufferReadBufferEXT GLuint framebuffer GLenum mode void glFramebufferRenderbuffer GLenum target GLenum attachment GLenum renderbuffertarget GLuint renderbuffer void glFramebufferRenderbufferEXT GLenum target GLenum attachment GLenum renderbuffertarget GLuint renderbuffer void glFramebufferRenderbufferOES GLenum target GLenum attachment GLenum renderbuffertarget GLuint renderbuffer void glFramebufferTexture GLenum target GLenum attachment GLuint texture GLint level void glFramebufferTexture1D GLenum target GLenum attachment GLenum textarget GLuint texture GLint level void glFramebufferTexture1DEXT GLenum target GLenum attachment GLenum textarget GLuint texture GLint level void glFramebufferTexture2D GLenum target GLenum attachment GLenum textarget GLuint texture GLint level void glFramebufferTexture2DEXT GLenum target GLenum attachment GLenum textarget GLuint texture GLint level void glFramebufferTexture2DMultisampleEXT GLenum target GLenum attachment GLenum textarget GLuint texture GLint level GLsizei samples void glFramebufferTexture2DMultisampleIMG GLenum target GLenum attachment GLenum textarget GLuint texture GLint level GLsizei samples void glFramebufferTexture2DOES GLenum target GLenum attachment GLenum textarget GLuint texture GLint level void glFramebufferTexture3D GLenum target GLenum attachment GLenum textarget GLuint texture GLint level GLint zoffset void glFramebufferTexture3DEXT GLenum target GLenum attachment GLenum textarget GLuint texture GLint level GLint zoffset void glFramebufferTexture3DOES GLenum target GLenum attachment GLenum textarget GLuint texture GLint level GLint zoffset void glFramebufferTextureARB GLenum target GLenum attachment GLuint texture GLint level void glFramebufferTextureEXT GLenum target GLenum attachment GLuint texture GLint level void glFramebufferTextureFaceARB GLenum target GLenum attachment GLuint texture GLint level GLenum face void glFramebufferTextureFaceEXT GLenum target GLenum attachment GLuint texture GLint level GLenum face void glFramebufferTextureLayer GLenum target GLenum attachment GLuint texture GLint level GLint layer void glFramebufferTextureLayerARB GLenum target GLenum attachment GLuint texture GLint level GLint layer void glFramebufferTextureLayerEXT GLenum target GLenum attachment GLuint texture GLint level GLint layer void glFreeObjectBufferATI GLuint buffer void glFrontFace GLenum mode void glFrustum GLdouble left GLdouble right GLdouble bottom GLdouble top GLdouble zNear GLdouble zFar void glFrustumf GLfloat l GLfloat r GLfloat b GLfloat t GLfloat n GLfloat f void glFrustumfOES GLfloat l GLfloat r GLfloat b GLfloat t GLfloat n GLfloat f void glFrustumx GLfixed l GLfixed r GLfixed b GLfixed t GLfixed n GLfixed f void glFrustumxOES GLfixed l GLfixed r GLfixed b GLfixed t GLfixed n GLfixed f GLuint glGenAsyncMarkersSGIX GLsizei range void glGenBuffers GLsizei n GLuint *buffers void glGenBuffersARB GLsizei n GLuint *buffers void glGenFencesAPPLE GLsizei n GLuint *fences void glGenFencesNV GLsizei n GLuint *fences GLuint glGenFragmentShadersATI GLuint range void glGenFramebuffers GLsizei n GLuint *framebuffers void glGenFramebuffersEXT GLsizei n GLuint *framebuffers void glGenFramebuffersOES GLsizei n GLuint *framebuffers GLuint glGenLists GLsizei range void glGenNamesAMD GLenum identifier GLuint num GLuint *names void glGenOcclusionQueriesNV GLsizei n GLuint *ids GLuint glGenPathsNV GLsizei range void glGenPerfMonitorsAMD GLsizei n GLuint *monitors void glGenProgramPipelines GLsizei n GLuint *pipelines void glGenProgramPipelinesEXT GLsizei n GLuint *pipelines void glGenProgramsARB GLsizei n GLuint *programs void glGenProgramsNV GLsizei n GLuint *programs void glGenQueries GLsizei n GLuint *ids void glGenQueriesARB GLsizei n GLuint *ids void glGenQueriesEXT GLsizei n GLuint *ids void glGenRenderbuffers GLsizei n GLuint *renderbuffers void glGenRenderbuffersEXT GLsizei n GLuint *renderbuffers void glGenRenderbuffersOES GLsizei n GLuint *renderbuffers void glGenSamplers GLsizei count GLuint *samplers GLuint glGenSymbolsEXT GLenum datatype GLenum storagetype GLenum range GLuint components void glGenTextures GLsizei n GLuint *textures void glGenTexturesEXT GLsizei n GLuint *textures void glGenTransformFeedbacks GLsizei n GLuint *ids void glGenTransformFeedbacksNV GLsizei n GLuint *ids void glGenVertexArrays GLsizei n GLuint *arrays void glGenVertexArraysAPPLE GLsizei n GLuint *arrays void glGenVertexArraysOES GLsizei n GLuint *arrays GLuint glGenVertexShadersEXT GLuint range void glGenerateMipmap GLenum target void glGenerateMipmapEXT GLenum target void glGenerateMipmapOES GLenum target void glGenerateMultiTexMipmapEXT GLenum texunit GLenum target void glGenerateTextureMipmap GLuint texture void glGenerateTextureMipmapEXT GLuint texture GLenum target void glGetActiveAtomicCounterBufferiv GLuint program GLuint bufferIndex GLenum pname GLint *params void glGetActiveAttrib GLuint program GLuint index GLsizei bufSize GLsizei *length GLint *size GLenum *type GLchar *name void glGetActiveAttribARB GLhandleARB programObj GLuint index GLsizei maxLength GLsizei *length GLint *size GLenum *type GLcharARB *name void glGetActiveSubroutineName GLuint program GLenum shadertype GLuint index GLsizei bufsize GLsizei *length GLchar *name void glGetActiveSubroutineUniformName GLuint program GLenum shadertype GLuint index GLsizei bufsize GLsizei *length GLchar *name void glGetActiveSubroutineUniformiv GLuint program GLenum shadertype GLuint index GLenum pname GLint *values void glGetActiveUniform GLuint program GLuint index GLsizei bufSize GLsizei *length GLint *size GLenum *type GLchar *name void glGetActiveUniformARB GLhandleARB programObj GLuint index GLsizei maxLength GLsizei *length GLint *size GLenum *type GLcharARB *name void glGetActiveUniformBlockName GLuint program GLuint uniformBlockIndex GLsizei bufSize GLsizei *length GLchar *uniformBlockName void glGetActiveUniformBlockiv GLuint program GLuint uniformBlockIndex GLenum pname GLint *params void glGetActiveUniformName GLuint program GLuint uniformIndex GLsizei bufSize GLsizei *length GLchar *uniformName void glGetActiveUniformsiv GLuint program GLsizei uniformCount const GLuint *uniformIndices GLenum pname GLint *params void glGetActiveVaryingNV GLuint program GLuint index GLsizei bufSize GLsizei *length GLsizei *size GLenum *type GLchar *name void glGetArrayObjectfvATI GLenum array GLenum pname GLfloat *params void glGetArrayObjectivATI GLenum array GLenum pname GLint *params void glGetAttachedObjectsARB GLhandleARB containerObj GLsizei maxCount GLsizei *count GLhandleARB *obj void glGetAttachedShaders GLuint program GLsizei maxCount GLsizei *count GLuint *shaders GLint glGetAttribLocation GLuint program const GLchar *name GLint glGetAttribLocationARB GLhandleARB programObj const GLcharARB *name void glGetBooleanIndexedvEXT GLenum target GLuint index GLboolean *data void glGetBooleani_v GLenum target GLuint index GLboolean *data void glGetBooleanv GLenum pname GLboolean *data void glGetBufferParameteri64v GLenum target GLenum pname GLint64 *params void glGetBufferParameteriv GLenum target GLenum pname GLint *params void glGetBufferParameterivARB GLenum target GLenum pname GLint *params void glGetBufferParameterui64vNV GLenum target GLenum pname GLuint64EXT *params void glGetBufferPointerv GLenum target GLenum pname void **params void glGetBufferPointervARB GLenum target GLenum pname void **params void glGetBufferPointervOES GLenum target GLenum pname void **params void glGetBufferSubData GLenum target GLintptr offset GLsizeiptr size void *data void glGetBufferSubDataARB GLenum target GLintptrARB offset GLsizeiptrARB size void *data void glGetClipPlane GLenum plane GLdouble *equation void glGetClipPlanef GLenum plane GLfloat *equation void glGetClipPlanefOES GLenum plane GLfloat *equation void glGetClipPlanex GLenum plane GLfixed *equation void glGetClipPlanexOES GLenum plane GLfixed *equation void glGetColorTable GLenum target GLenum format GLenum type void *table void glGetColorTableEXT GLenum target GLenum format GLenum type void *data void glGetColorTableParameterfv GLenum target GLenum pname GLfloat *params void glGetColorTableParameterfvEXT GLenum target GLenum pname GLfloat *params void glGetColorTableParameterfvSGI GLenum target GLenum pname GLfloat *params void glGetColorTableParameteriv GLenum target GLenum pname GLint *params void glGetColorTableParameterivEXT GLenum target GLenum pname GLint *params void glGetColorTableParameterivSGI GLenum target GLenum pname GLint *params void glGetColorTableSGI GLenum target GLenum format GLenum type void *table void glGetCombinerInputParameterfvNV GLenum stage GLenum portion GLenum variable GLenum pname GLfloat *params void glGetCombinerInputParameterivNV GLenum stage GLenum portion GLenum variable GLenum pname GLint *params void glGetCombinerOutputParameterfvNV GLenum stage GLenum portion GLenum pname GLfloat *params void glGetCombinerOutputParameterivNV GLenum stage GLenum portion GLenum pname GLint *params void glGetCombinerStageParameterfvNV GLenum stage GLenum pname GLfloat *params void glGetCompressedMultiTexImageEXT GLenum texunit GLenum target GLint lod void *img void glGetCompressedTexImage GLenum target GLint level void *img void glGetCompressedTexImageARB GLenum target GLint level void *img void glGetCompressedTextureImage GLuint texture GLint level GLsizei bufSize void *pixels void glGetCompressedTextureImageEXT GLuint texture GLenum target GLint lod void *img void glGetCompressedTextureSubImage GLuint texture GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLsizei bufSize void *pixels void glGetConvolutionFilter GLenum target GLenum format GLenum type void *image void glGetConvolutionFilterEXT GLenum target GLenum format GLenum type void *image void glGetConvolutionParameterfv GLenum target GLenum pname GLfloat *params void glGetConvolutionParameterfvEXT GLenum target GLenum pname GLfloat *params void glGetConvolutionParameteriv GLenum target GLenum pname GLint *params void glGetConvolutionParameterivEXT GLenum target GLenum pname GLint *params void glGetConvolutionParameterxvOES GLenum target GLenum pname GLfixed *params GLuint glGetDebugMessageLog GLuint count GLsizei bufSize GLenum *sources GLenum *types GLuint *ids GLenum *severities GLsizei *lengths GLchar *messageLog GLuint glGetDebugMessageLogAMD GLuint count GLsizei bufsize GLenum *categories GLuint *severities GLuint *ids GLsizei *lengths GLchar *message GLuint glGetDebugMessageLogARB GLuint count GLsizei bufSize GLenum *sources GLenum *types GLuint *ids GLenum *severities GLsizei *lengths GLchar *messageLog GLuint glGetDebugMessageLogKHR GLuint count GLsizei bufSize GLenum *sources GLenum *types GLuint *ids GLenum *severities GLsizei *lengths GLchar *messageLog void glGetDetailTexFuncSGIS GLenum target GLfloat *points void glGetDoubleIndexedvEXT GLenum target GLuint index GLdouble *data void glGetDoublei_v GLenum target GLuint index GLdouble *data void glGetDoublei_vEXT GLenum pname GLuint index GLdouble *params void glGetDoublev GLenum pname GLdouble *data void glGetDriverControlStringQCOM GLuint driverControl GLsizei bufSize GLsizei *length GLchar *driverControlString void glGetDriverControlsQCOM GLint *num GLsizei size GLuint *driverControls GLenum glGetError void glGetFenceivNV GLuint fence GLenum pname GLint *params void glGetFinalCombinerInputParameterfvNV GLenum variable GLenum pname GLfloat *params void glGetFinalCombinerInputParameterivNV GLenum variable GLenum pname GLint *params void glGetFirstPerfQueryIdINTEL GLuint *queryId void glGetFixedv GLenum pname GLfixed *params void glGetFixedvOES GLenum pname GLfixed *params void glGetFloatIndexedvEXT GLenum target GLuint index GLfloat *data void glGetFloati_v GLenum target GLuint index GLfloat *data void glGetFloati_vNV GLenum target GLuint index GLfloat *data void glGetFloati_vEXT GLenum pname GLuint index GLfloat *params void glGetFloatv GLenum pname GLfloat *data void glGetFogFuncSGIS GLfloat *points GLint glGetFragDataIndex GLuint program const GLchar *name GLint glGetFragDataLocation GLuint program const GLchar *name GLint glGetFragDataLocationEXT GLuint program const GLchar *name void glGetFragmentLightfvSGIX GLenum light GLenum pname GLfloat *params void glGetFragmentLightivSGIX GLenum light GLenum pname GLint *params void glGetFragmentMaterialfvSGIX GLenum face GLenum pname GLfloat *params void glGetFragmentMaterialivSGIX GLenum face GLenum pname GLint *params void glGetFramebufferAttachmentParameteriv GLenum target GLenum attachment GLenum pname GLint *params void glGetFramebufferAttachmentParameterivEXT GLenum target GLenum attachment GLenum pname GLint *params void glGetFramebufferAttachmentParameterivOES GLenum target GLenum attachment GLenum pname GLint *params void glGetFramebufferParameteriv GLenum target GLenum pname GLint *params void glGetFramebufferParameterivEXT GLuint framebuffer GLenum pname GLint *params GLenum glGetGraphicsResetStatus GLenum glGetGraphicsResetStatusARB GLenum glGetGraphicsResetStatusEXT GLenum glGetGraphicsResetStatusKHR GLhandleARB glGetHandleARB GLenum pname void glGetHistogram GLenum target GLboolean reset GLenum format GLenum type void *values void glGetHistogramEXT GLenum target GLboolean reset GLenum format GLenum type void *values void glGetHistogramParameterfv GLenum target GLenum pname GLfloat *params void glGetHistogramParameterfvEXT GLenum target GLenum pname GLfloat *params void glGetHistogramParameteriv GLenum target GLenum pname GLint *params void glGetHistogramParameterivEXT GLenum target GLenum pname GLint *params void glGetHistogramParameterxvOES GLenum target GLenum pname GLfixed *params GLuint64 glGetImageHandleARB GLuint texture GLint level GLboolean layered GLint layer GLenum format GLuint64 glGetImageHandleNV GLuint texture GLint level GLboolean layered GLint layer GLenum format void glGetImageTransformParameterfvHP GLenum target GLenum pname GLfloat *params void glGetImageTransformParameterivHP GLenum target GLenum pname GLint *params void glGetInfoLogARB GLhandleARB obj GLsizei maxLength GLsizei *length GLcharARB *infoLog GLint glGetInstrumentsSGIX void glGetInteger64i_v GLenum target GLuint index GLint64 *data void glGetInteger64v GLenum pname GLint64 *data void glGetInteger64vAPPLE GLenum pname GLint64 *params void glGetIntegerIndexedvEXT GLenum target GLuint index GLint *data void glGetIntegeri_v GLenum target GLuint index GLint *data void glGetIntegeri_vEXT GLenum target GLuint index GLint *data void glGetIntegerui64i_vNV GLenum value GLuint index GLuint64EXT *result void glGetIntegerui64vNV GLenum value GLuint64EXT *result void glGetIntegerv GLenum pname GLint *data void glGetInternalformati64v GLenum target GLenum internalformat GLenum pname GLsizei bufSize GLint64 *params void glGetInternalformativ GLenum target GLenum internalformat GLenum pname GLsizei bufSize GLint *params void glGetInternalformatSampleivNV GLenum target GLenum internalformat GLsizei samples GLenum pname GLsizei bufSize GLint *params void glGetInvariantBooleanvEXT GLuint id GLenum value GLboolean *data void glGetInvariantFloatvEXT GLuint id GLenum value GLfloat *data void glGetInvariantIntegervEXT GLuint id GLenum value GLint *data void glGetLightfv GLenum light GLenum pname GLfloat *params void glGetLightiv GLenum light GLenum pname GLint *params void glGetLightxOES GLenum light GLenum pname GLfixed *params void glGetLightxv GLenum light GLenum pname GLfixed *params void glGetLightxvOES GLenum light GLenum pname GLfixed *params void glGetListParameterfvSGIX GLuint list GLenum pname GLfloat *params void glGetListParameterivSGIX GLuint list GLenum pname GLint *params void glGetLocalConstantBooleanvEXT GLuint id GLenum value GLboolean *data void glGetLocalConstantFloatvEXT GLuint id GLenum value GLfloat *data void glGetLocalConstantIntegervEXT GLuint id GLenum value GLint *data void glGetMapAttribParameterfvNV GLenum target GLuint index GLenum pname GLfloat *params void glGetMapAttribParameterivNV GLenum target GLuint index GLenum pname GLint *params void glGetMapControlPointsNV GLenum target GLuint index GLenum type GLsizei ustride GLsizei vstride GLboolean packed void *points void glGetMapParameterfvNV GLenum target GLenum pname GLfloat *params void glGetMapParameterivNV GLenum target GLenum pname GLint *params void glGetMapdv GLenum target GLenum query GLdouble *v void glGetMapfv GLenum target GLenum query GLfloat *v void glGetMapiv GLenum target GLenum query GLint *v void glGetMapxvOES GLenum target GLenum query GLfixed *v void glGetMaterialfv GLenum face GLenum pname GLfloat *params void glGetMaterialiv GLenum face GLenum pname GLint *params void glGetMaterialxOES GLenum face GLenum pname GLfixed param void glGetMaterialxv GLenum face GLenum pname GLfixed *params void glGetMaterialxvOES GLenum face GLenum pname GLfixed *params void glGetMinmax GLenum target GLboolean reset GLenum format GLenum type void *values void glGetMinmaxEXT GLenum target GLboolean reset GLenum format GLenum type void *values void glGetMinmaxParameterfv GLenum target GLenum pname GLfloat *params void glGetMinmaxParameterfvEXT GLenum target GLenum pname GLfloat *params void glGetMinmaxParameteriv GLenum target GLenum pname GLint *params void glGetMinmaxParameterivEXT GLenum target GLenum pname GLint *params void glGetMultiTexEnvfvEXT GLenum texunit GLenum target GLenum pname GLfloat *params void glGetMultiTexEnvivEXT GLenum texunit GLenum target GLenum pname GLint *params void glGetMultiTexGendvEXT GLenum texunit GLenum coord GLenum pname GLdouble *params void glGetMultiTexGenfvEXT GLenum texunit GLenum coord GLenum pname GLfloat *params void glGetMultiTexGenivEXT GLenum texunit GLenum coord GLenum pname GLint *params void glGetMultiTexImageEXT GLenum texunit GLenum target GLint level GLenum format GLenum type void *pixels void glGetMultiTexLevelParameterfvEXT GLenum texunit GLenum target GLint level GLenum pname GLfloat *params void glGetMultiTexLevelParameterivEXT GLenum texunit GLenum target GLint level GLenum pname GLint *params void glGetMultiTexParameterIivEXT GLenum texunit GLenum target GLenum pname GLint *params void glGetMultiTexParameterIuivEXT GLenum texunit GLenum target GLenum pname GLuint *params void glGetMultiTexParameterfvEXT GLenum texunit GLenum target GLenum pname GLfloat *params void glGetMultiTexParameterivEXT GLenum texunit GLenum target GLenum pname GLint *params void glGetMultisamplefv GLenum pname GLuint index GLfloat *val void glGetMultisamplefvNV GLenum pname GLuint index GLfloat *val void glGetNamedBufferParameteri64v GLuint buffer GLenum pname GLint64 *params void glGetNamedBufferParameteriv GLuint buffer GLenum pname GLint *params void glGetNamedBufferParameterivEXT GLuint buffer GLenum pname GLint *params void glGetNamedBufferParameterui64vNV GLuint buffer GLenum pname GLuint64EXT *params void glGetNamedBufferPointerv GLuint buffer GLenum pname void **params void glGetNamedBufferPointervEXT GLuint buffer GLenum pname void **params void glGetNamedBufferSubData GLuint buffer GLintptr offset GLsizei size void *data void glGetNamedBufferSubDataEXT GLuint buffer GLintptr offset GLsizeiptr size void *data void glGetNamedFramebufferAttachmentParameteriv GLuint framebuffer GLenum attachment GLenum pname GLint *params void glGetNamedFramebufferAttachmentParameterivEXT GLuint framebuffer GLenum attachment GLenum pname GLint *params void glGetNamedFramebufferParameteriv GLuint framebuffer GLenum pname GLint *param void glGetNamedFramebufferParameterivEXT GLuint framebuffer GLenum pname GLint *params void glGetNamedProgramLocalParameterIivEXT GLuint program GLenum target GLuint index GLint *params void glGetNamedProgramLocalParameterIuivEXT GLuint program GLenum target GLuint index GLuint *params void glGetNamedProgramLocalParameterdvEXT GLuint program GLenum target GLuint index GLdouble *params void glGetNamedProgramLocalParameterfvEXT GLuint program GLenum target GLuint index GLfloat *params void glGetNamedProgramStringEXT GLuint program GLenum target GLenum pname void *string void glGetNamedProgramivEXT GLuint program GLenum target GLenum pname GLint *params void glGetNamedRenderbufferParameteriv GLuint renderbuffer GLenum pname GLint *params void glGetNamedRenderbufferParameterivEXT GLuint renderbuffer GLenum pname GLint *params void glGetNamedStringARB GLint namelen const GLchar *name GLsizei bufSize GLint *stringlen GLchar *string void glGetNamedStringivARB GLint namelen const GLchar *name GLenum pname GLint *params void glGetNextPerfQueryIdINTEL GLuint queryId GLuint *nextQueryId void glGetObjectBufferfvATI GLuint buffer GLenum pname GLfloat *params void glGetObjectBufferivATI GLuint buffer GLenum pname GLint *params void glGetObjectLabel GLenum identifier GLuint name GLsizei bufSize GLsizei *length GLchar *label void glGetObjectLabelEXT GLenum type GLuint object GLsizei bufSize GLsizei *length GLchar *label void glGetObjectLabelKHR GLenum identifier GLuint name GLsizei bufSize GLsizei *length GLchar *label void glGetObjectParameterfvARB GLhandleARB obj GLenum pname GLfloat *params void glGetObjectParameterivAPPLE GLenum objectType GLuint name GLenum pname GLint *params void glGetObjectParameterivARB GLhandleARB obj GLenum pname GLint *params void glGetObjectPtrLabel const void *ptr GLsizei bufSize GLsizei *length GLchar *label void glGetObjectPtrLabelKHR const void *ptr GLsizei bufSize GLsizei *length GLchar *label void glGetOcclusionQueryivNV GLuint id GLenum pname GLint *params void glGetOcclusionQueryuivNV GLuint id GLenum pname GLuint *params void glGetPathColorGenfvNV GLenum color GLenum pname GLfloat *value void glGetPathColorGenivNV GLenum color GLenum pname GLint *value void glGetPathCommandsNV GLuint path GLubyte *commands void glGetPathCoordsNV GLuint path GLfloat *coords void glGetPathDashArrayNV GLuint path GLfloat *dashArray GLfloat glGetPathLengthNV GLuint path GLsizei startSegment GLsizei numSegments void glGetPathMetricRangeNV GLbitfield metricQueryMask GLuint firstPathName GLsizei numPaths GLsizei stride GLfloat *metrics void glGetPathMetricsNV GLbitfield metricQueryMask GLsizei numPaths GLenum pathNameType const void *paths GLuint pathBase GLsizei stride GLfloat *metrics void glGetPathParameterfvNV GLuint path GLenum pname GLfloat *value void glGetPathParameterivNV GLuint path GLenum pname GLint *value void glGetPathSpacingNV GLenum pathListMode GLsizei numPaths GLenum pathNameType const void *paths GLuint pathBase GLfloat advanceScale GLfloat kerningScale GLenum transformType GLfloat *returnedSpacing void glGetPathTexGenfvNV GLenum texCoordSet GLenum pname GLfloat *value void glGetPathTexGenivNV GLenum texCoordSet GLenum pname GLint *value void glGetPerfCounterInfoINTEL GLuint queryId GLuint counterId GLuint counterNameLength GLchar *counterName GLuint counterDescLength GLchar *counterDesc GLuint *counterOffset GLuint *counterDataSize GLuint *counterTypeEnum GLuint *counterDataTypeEnum GLuint64 *rawCounterMaxValue void glGetPerfMonitorCounterDataAMD GLuint monitor GLenum pname GLsizei dataSize GLuint *data GLint *bytesWritten void glGetPerfMonitorCounterInfoAMD GLuint group GLuint counter GLenum pname void *data void glGetPerfMonitorCounterStringAMD GLuint group GLuint counter GLsizei bufSize GLsizei *length GLchar *counterString void glGetPerfMonitorCountersAMD GLuint group GLint *numCounters GLint *maxActiveCounters GLsizei counterSize GLuint *counters void glGetPerfMonitorGroupStringAMD GLuint group GLsizei bufSize GLsizei *length GLchar *groupString void glGetPerfMonitorGroupsAMD GLint *numGroups GLsizei groupsSize GLuint *groups void glGetPerfQueryDataINTEL GLuint queryHandle GLuint flags GLsizei dataSize GLvoid *data GLuint *bytesWritten void glGetPerfQueryIdByNameINTEL GLchar *queryName GLuint *queryId void glGetPerfQueryInfoINTEL GLuint queryId GLuint queryNameLength GLchar *queryName GLuint *dataSize GLuint *noCounters GLuint *noInstances GLuint *capsMask void glGetPixelMapfv GLenum map GLfloat *values void glGetPixelMapuiv GLenum map GLuint *values void glGetPixelMapusv GLenum map GLushort *values void glGetPixelMapxv GLenum map GLint size GLfixed *values void glGetPixelTexGenParameterfvSGIS GLenum pname GLfloat *params void glGetPixelTexGenParameterivSGIS GLenum pname GLint *params void glGetPixelTransformParameterfvEXT GLenum target GLenum pname GLfloat *params void glGetPixelTransformParameterivEXT GLenum target GLenum pname GLint *params void glGetPointerIndexedvEXT GLenum target GLuint index void **data void glGetPointeri_vEXT GLenum pname GLuint index void **params void glGetPointerv GLenum pname void **params void glGetPointervEXT GLenum pname void **params void glGetPointervKHR GLenum pname void **params void glGetPolygonStipple GLubyte *mask void glGetProgramBinary GLuint program GLsizei bufSize GLsizei *length GLenum *binaryFormat void *binary void glGetProgramBinaryOES GLuint program GLsizei bufSize GLsizei *length GLenum *binaryFormat void *binary void glGetProgramEnvParameterIivNV GLenum target GLuint index GLint *params void glGetProgramEnvParameterIuivNV GLenum target GLuint index GLuint *params void glGetProgramEnvParameterdvARB GLenum target GLuint index GLdouble *params void glGetProgramEnvParameterfvARB GLenum target GLuint index GLfloat *params void glGetProgramInfoLog GLuint program GLsizei bufSize GLsizei *length GLchar *infoLog void glGetProgramInterfaceiv GLuint program GLenum programInterface GLenum pname GLint *params void glGetProgramLocalParameterIivNV GLenum target GLuint index GLint *params void glGetProgramLocalParameterIuivNV GLenum target GLuint index GLuint *params void glGetProgramLocalParameterdvARB GLenum target GLuint index GLdouble *params void glGetProgramLocalParameterfvARB GLenum target GLuint index GLfloat *params void glGetProgramNamedParameterdvNV GLuint id GLsizei len const GLubyte *name GLdouble *params void glGetProgramNamedParameterfvNV GLuint id GLsizei len const GLubyte *name GLfloat *params void glGetProgramParameterdvNV GLenum target GLuint index GLenum pname GLdouble *params void glGetProgramParameterfvNV GLenum target GLuint index GLenum pname GLfloat *params void glGetProgramPipelineInfoLog GLuint pipeline GLsizei bufSize GLsizei *length GLchar *infoLog void glGetProgramPipelineInfoLogEXT GLuint pipeline GLsizei bufSize GLsizei *length GLchar *infoLog void glGetProgramPipelineiv GLuint pipeline GLenum pname GLint *params void glGetProgramPipelineivEXT GLuint pipeline GLenum pname GLint *params GLuint glGetProgramResourceIndex GLuint program GLenum programInterface const GLchar *name GLint glGetProgramResourceLocation GLuint program GLenum programInterface const GLchar *name GLint glGetProgramResourceLocationIndex GLuint program GLenum programInterface const GLchar *name void glGetProgramResourceName GLuint program GLenum programInterface GLuint index GLsizei bufSize GLsizei *length GLchar *name void glGetProgramResourcefvNV GLuint program GLenum programInterface GLuint index GLsizei propCount const GLenum *props GLsizei bufSize GLsizei *length GLfloat *params void glGetProgramResourceiv GLuint program GLenum programInterface GLuint index GLsizei propCount const GLenum *props GLsizei bufSize GLsizei *length GLint *params void glGetProgramStageiv GLuint program GLenum shadertype GLenum pname GLint *values void glGetProgramStringARB GLenum target GLenum pname void *string void glGetProgramStringNV GLuint id GLenum pname GLubyte *program void glGetProgramSubroutineParameteruivNV GLenum target GLuint index GLuint *param void glGetProgramiv GLuint program GLenum pname GLint *params void glGetProgramivARB GLenum target GLenum pname GLint *params void glGetProgramivNV GLuint id GLenum pname GLint *params void glGetQueryBufferObjecti64v GLuint id GLuint buffer GLenum pname GLintptr offset void glGetQueryBufferObjectiv GLuint id GLuint buffer GLenum pname GLintptr offset void glGetQueryBufferObjectui64v GLuint id GLuint buffer GLenum pname GLintptr offset void glGetQueryBufferObjectuiv GLuint id GLuint buffer GLenum pname GLintptr offset void glGetQueryIndexediv GLenum target GLuint index GLenum pname GLint *params void glGetQueryObjecti64v GLuint id GLenum pname GLint64 *params void glGetQueryObjecti64vEXT GLuint id GLenum pname GLint64 *params void glGetQueryObjectiv GLuint id GLenum pname GLint *params void glGetQueryObjectivARB GLuint id GLenum pname GLint *params void glGetQueryObjectivEXT GLuint id GLenum pname GLint *params void glGetQueryObjectui64v GLuint id GLenum pname GLuint64 *params void glGetQueryObjectui64vEXT GLuint id GLenum pname GLuint64 *params void glGetQueryObjectuiv GLuint id GLenum pname GLuint *params void glGetQueryObjectuivARB GLuint id GLenum pname GLuint *params void glGetQueryObjectuivEXT GLuint id GLenum pname GLuint *params void glGetQueryiv GLenum target GLenum pname GLint *params void glGetQueryivARB GLenum target GLenum pname GLint *params void glGetQueryivEXT GLenum target GLenum pname GLint *params void glGetRenderbufferParameteriv GLenum target GLenum pname GLint *params void glGetRenderbufferParameterivEXT GLenum target GLenum pname GLint *params void glGetRenderbufferParameterivOES GLenum target GLenum pname GLint *params void glGetSamplerParameterIiv GLuint sampler GLenum pname GLint *params void glGetSamplerParameterIivEXT GLuint sampler GLenum pname GLint *params void glGetSamplerParameterIuiv GLuint sampler GLenum pname GLuint *params void glGetSamplerParameterIuivEXT GLuint sampler GLenum pname GLuint *params void glGetSamplerParameterfv GLuint sampler GLenum pname GLfloat *params void glGetSamplerParameteriv GLuint sampler GLenum pname GLint *params void glGetSeparableFilter GLenum target GLenum format GLenum type void *row void *column void *span void glGetSeparableFilterEXT GLenum target GLenum format GLenum type void *row void *column void *span void glGetShaderInfoLog GLuint shader GLsizei bufSize GLsizei *length GLchar *infoLog void glGetShaderPrecisionFormat GLenum shadertype GLenum precisiontype GLint *range GLint *precision void glGetShaderSource GLuint shader GLsizei bufSize GLsizei *length GLchar *source void glGetShaderSourceARB GLhandleARB obj GLsizei maxLength GLsizei *length GLcharARB *source void glGetShaderiv GLuint shader GLenum pname GLint *params void glGetSharpenTexFuncSGIS GLenum target GLfloat *points const GLubyte *glGetString GLenum name const GLubyte *glGetStringi GLenum name GLuint index GLuint glGetSubroutineIndex GLuint program GLenum shadertype const GLchar *name GLint glGetSubroutineUniformLocation GLuint program GLenum shadertype const GLchar *name void glGetSynciv GLsync sync GLenum pname GLsizei bufSize GLsizei *length GLint *values void glGetSyncivAPPLE GLsync sync GLenum pname GLsizei bufSize GLsizei *length GLint *values void glGetTexBumpParameterfvATI GLenum pname GLfloat *param void glGetTexBumpParameterivATI GLenum pname GLint *param void glGetTexEnvfv GLenum target GLenum pname GLfloat *params void glGetTexEnviv GLenum target GLenum pname GLint *params void glGetTexEnvxv GLenum target GLenum pname GLfixed *params void glGetTexEnvxvOES GLenum target GLenum pname GLfixed *params void glGetTexFilterFuncSGIS GLenum target GLenum filter GLfloat *weights void glGetTexGendv GLenum coord GLenum pname GLdouble *params void glGetTexGenfv GLenum coord GLenum pname GLfloat *params void glGetTexGenfvOES GLenum coord GLenum pname GLfloat *params void glGetTexGeniv GLenum coord GLenum pname GLint *params void glGetTexGenivOES GLenum coord GLenum pname GLint *params void glGetTexGenxvOES GLenum coord GLenum pname GLfixed *params void glGetTexImage GLenum target GLint level GLenum format GLenum type void *pixels void glGetTexLevelParameterfv GLenum target GLint level GLenum pname GLfloat *params void glGetTexLevelParameteriv GLenum target GLint level GLenum pname GLint *params void glGetTexLevelParameterxvOES GLenum target GLint level GLenum pname GLfixed *params void glGetTexParameterIiv GLenum target GLenum pname GLint *params void glGetTexParameterIivEXT GLenum target GLenum pname GLint *params void glGetTexParameterIuiv GLenum target GLenum pname GLuint *params void glGetTexParameterIuivEXT GLenum target GLenum pname GLuint *params void glGetTexParameterPointervAPPLE GLenum target GLenum pname void **params void glGetTexParameterfv GLenum target GLenum pname GLfloat *params void glGetTexParameteriv GLenum target GLenum pname GLint *params void glGetTexParameterxv GLenum target GLenum pname GLfixed *params void glGetTexParameterxvOES GLenum target GLenum pname GLfixed *params GLuint64 glGetTextureHandleARB GLuint texture GLuint64 glGetTextureHandleNV GLuint texture void glGetTextureImage GLuint texture GLint level GLenum format GLenum type GLsizei bufSize void *pixels void glGetTextureImageEXT GLuint texture GLenum target GLint level GLenum format GLenum type void *pixels void glGetTextureLevelParameterfv GLuint texture GLint level GLenum pname GLfloat *params void glGetTextureLevelParameterfvEXT GLuint texture GLenum target GLint level GLenum pname GLfloat *params void glGetTextureLevelParameteriv GLuint texture GLint level GLenum pname GLint *params void glGetTextureLevelParameterivEXT GLuint texture GLenum target GLint level GLenum pname GLint *params void glGetTextureParameterIiv GLuint texture GLenum pname GLint *params void glGetTextureParameterIivEXT GLuint texture GLenum target GLenum pname GLint *params void glGetTextureParameterIuiv GLuint texture GLenum pname GLuint *params void glGetTextureParameterIuivEXT GLuint texture GLenum target GLenum pname GLuint *params void glGetTextureParameterfv GLuint texture GLenum pname GLfloat *params void glGetTextureParameterfvEXT GLuint texture GLenum target GLenum pname GLfloat *params void glGetTextureParameteriv GLuint texture GLenum pname GLint *params void glGetTextureParameterivEXT GLuint texture GLenum target GLenum pname GLint *params GLuint64 glGetTextureSamplerHandleARB GLuint texture GLuint sampler GLuint64 glGetTextureSamplerHandleNV GLuint texture GLuint sampler void glGetTextureSubImage GLuint texture GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLenum type GLsizei bufSize void *pixels void glGetTrackMatrixivNV GLenum target GLuint address GLenum pname GLint *params void glGetTransformFeedbackVarying GLuint program GLuint index GLsizei bufSize GLsizei *length GLsizei *size GLenum *type GLchar *name void glGetTransformFeedbackVaryingEXT GLuint program GLuint index GLsizei bufSize GLsizei *length GLsizei *size GLenum *type GLchar *name void glGetTransformFeedbackVaryingNV GLuint program GLuint index GLint *location void glGetTransformFeedbacki64_v GLuint xfb GLenum pname GLuint index GLint64 *param void glGetTransformFeedbacki_v GLuint xfb GLenum pname GLuint index GLint *param void glGetTransformFeedbackiv GLuint xfb GLenum pname GLint *param void glGetTranslatedShaderSourceANGLE GLuint shader GLsizei bufsize GLsizei *length GLchar *source GLuint glGetUniformBlockIndex GLuint program const GLchar *uniformBlockName GLint glGetUniformBufferSizeEXT GLuint program GLint location void glGetUniformIndices GLuint program GLsizei uniformCount const GLchar *const*uniformNames GLuint *uniformIndices GLint glGetUniformLocation GLuint program const GLchar *name GLint glGetUniformLocationARB GLhandleARB programObj const GLcharARB *name GLintptr glGetUniformOffsetEXT GLuint program GLint location void glGetUniformSubroutineuiv GLenum shadertype GLint location GLuint *params void glGetUniformdv GLuint program GLint location GLdouble *params void glGetUniformfv GLuint program GLint location GLfloat *params void glGetUniformfvARB GLhandleARB programObj GLint location GLfloat *params void glGetUniformi64vNV GLuint program GLint location GLint64EXT *params void glGetUniformiv GLuint program GLint location GLint *params void glGetUniformivARB GLhandleARB programObj GLint location GLint *params void glGetUniformui64vNV GLuint program GLint location GLuint64EXT *params void glGetUniformuiv GLuint program GLint location GLuint *params void glGetUniformuivEXT GLuint program GLint location GLuint *params void glGetVariantArrayObjectfvATI GLuint id GLenum pname GLfloat *params void glGetVariantArrayObjectivATI GLuint id GLenum pname GLint *params void glGetVariantBooleanvEXT GLuint id GLenum value GLboolean *data void glGetVariantFloatvEXT GLuint id GLenum value GLfloat *data void glGetVariantIntegervEXT GLuint id GLenum value GLint *data void glGetVariantPointervEXT GLuint id GLenum value void **data GLint glGetVaryingLocationNV GLuint program const GLchar *name void glGetVertexArrayIndexed64iv GLuint vaobj GLuint index GLenum pname GLint64 *param void glGetVertexArrayIndexediv GLuint vaobj GLuint index GLenum pname GLint *param void glGetVertexArrayIntegeri_vEXT GLuint vaobj GLuint index GLenum pname GLint *param void glGetVertexArrayIntegervEXT GLuint vaobj GLenum pname GLint *param void glGetVertexArrayPointeri_vEXT GLuint vaobj GLuint index GLenum pname void **param void glGetVertexArrayPointervEXT GLuint vaobj GLenum pname void **param void glGetVertexArrayiv GLuint vaobj GLenum pname GLint *param void glGetVertexAttribArrayObjectfvATI GLuint index GLenum pname GLfloat *params void glGetVertexAttribArrayObjectivATI GLuint index GLenum pname GLint *params void glGetVertexAttribIiv GLuint index GLenum pname GLint *params void glGetVertexAttribIivEXT GLuint index GLenum pname GLint *params void glGetVertexAttribIuiv GLuint index GLenum pname GLuint *params void glGetVertexAttribIuivEXT GLuint index GLenum pname GLuint *params void glGetVertexAttribLdv GLuint index GLenum pname GLdouble *params void glGetVertexAttribLdvEXT GLuint index GLenum pname GLdouble *params void glGetVertexAttribLi64vNV GLuint index GLenum pname GLint64EXT *params void glGetVertexAttribLui64vARB GLuint index GLenum pname GLuint64EXT *params void glGetVertexAttribLui64vNV GLuint index GLenum pname GLuint64EXT *params void glGetVertexAttribPointerv GLuint index GLenum pname void **pointer void glGetVertexAttribPointervARB GLuint index GLenum pname void **pointer void glGetVertexAttribPointervNV GLuint index GLenum pname void **pointer void glGetVertexAttribdv GLuint index GLenum pname GLdouble *params void glGetVertexAttribdvARB GLuint index GLenum pname GLdouble *params void glGetVertexAttribdvNV GLuint index GLenum pname GLdouble *params void glGetVertexAttribfv GLuint index GLenum pname GLfloat *params void glGetVertexAttribfvARB GLuint index GLenum pname GLfloat *params void glGetVertexAttribfvNV GLuint index GLenum pname GLfloat *params void glGetVertexAttribiv GLuint index GLenum pname GLint *params void glGetVertexAttribivARB GLuint index GLenum pname GLint *params void glGetVertexAttribivNV GLuint index GLenum pname GLint *params void glGetVideoCaptureStreamdvNV GLuint video_capture_slot GLuint stream GLenum pname GLdouble *params void glGetVideoCaptureStreamfvNV GLuint video_capture_slot GLuint stream GLenum pname GLfloat *params void glGetVideoCaptureStreamivNV GLuint video_capture_slot GLuint stream GLenum pname GLint *params void glGetVideoCaptureivNV GLuint video_capture_slot GLenum pname GLint *params void glGetVideoi64vNV GLuint video_slot GLenum pname GLint64EXT *params void glGetVideoivNV GLuint video_slot GLenum pname GLint *params void glGetVideoui64vNV GLuint video_slot GLenum pname GLuint64EXT *params void glGetVideouivNV GLuint video_slot GLenum pname GLuint *params void glGetnColorTable GLenum target GLenum format GLenum type GLsizei bufSize void *table void glGetnColorTableARB GLenum target GLenum format GLenum type GLsizei bufSize void *table void glGetnCompressedTexImage GLenum target GLint lod GLsizei bufSize void *pixels void glGetnCompressedTexImageARB GLenum target GLint lod GLsizei bufSize void *img void glGetnConvolutionFilter GLenum target GLenum format GLenum type GLsizei bufSize void *image void glGetnConvolutionFilterARB GLenum target GLenum format GLenum type GLsizei bufSize void *image void glGetnHistogram GLenum target GLboolean reset GLenum format GLenum type GLsizei bufSize void *values void glGetnHistogramARB GLenum target GLboolean reset GLenum format GLenum type GLsizei bufSize void *values void glGetnMapdv GLenum target GLenum query GLsizei bufSize GLdouble *v void glGetnMapdvARB GLenum target GLenum query GLsizei bufSize GLdouble *v void glGetnMapfv GLenum target GLenum query GLsizei bufSize GLfloat *v void glGetnMapfvARB GLenum target GLenum query GLsizei bufSize GLfloat *v void glGetnMapiv GLenum target GLenum query GLsizei bufSize GLint *v void glGetnMapivARB GLenum target GLenum query GLsizei bufSize GLint *v void glGetnMinmax GLenum target GLboolean reset GLenum format GLenum type GLsizei bufSize void *values void glGetnMinmaxARB GLenum target GLboolean reset GLenum format GLenum type GLsizei bufSize void *values void glGetnPixelMapfv GLenum map GLsizei bufSize GLfloat *values void glGetnPixelMapfvARB GLenum map GLsizei bufSize GLfloat *values void glGetnPixelMapuiv GLenum map GLsizei bufSize GLuint *values void glGetnPixelMapuivARB GLenum map GLsizei bufSize GLuint *values void glGetnPixelMapusv GLenum map GLsizei bufSize GLushort *values void glGetnPixelMapusvARB GLenum map GLsizei bufSize GLushort *values void glGetnPolygonStipple GLsizei bufSize GLubyte *pattern void glGetnPolygonStippleARB GLsizei bufSize GLubyte *pattern void glGetnSeparableFilter GLenum target GLenum format GLenum type GLsizei rowBufSize void *row GLsizei columnBufSize void *column void *span void glGetnSeparableFilterARB GLenum target GLenum format GLenum type GLsizei rowBufSize void *row GLsizei columnBufSize void *column void *span void glGetnTexImage GLenum target GLint level GLenum format GLenum type GLsizei bufSize void *pixels void glGetnTexImageARB GLenum target GLint level GLenum format GLenum type GLsizei bufSize void *img void glGetnUniformdv GLuint program GLint location GLsizei bufSize GLdouble *params void glGetnUniformdvARB GLuint program GLint location GLsizei bufSize GLdouble *params void glGetnUniformfv GLuint program GLint location GLsizei bufSize GLfloat *params void glGetnUniformfvARB GLuint program GLint location GLsizei bufSize GLfloat *params void glGetnUniformfvEXT GLuint program GLint location GLsizei bufSize GLfloat *params void glGetnUniformfvKHR GLuint program GLint location GLsizei bufSize GLfloat *params void glGetnUniformiv GLuint program GLint location GLsizei bufSize GLint *params void glGetnUniformivARB GLuint program GLint location GLsizei bufSize GLint *params void glGetnUniformivEXT GLuint program GLint location GLsizei bufSize GLint *params void glGetnUniformivKHR GLuint program GLint location GLsizei bufSize GLint *params void glGetnUniformuiv GLuint program GLint location GLsizei bufSize GLuint *params void glGetnUniformuivARB GLuint program GLint location GLsizei bufSize GLuint *params void glGetnUniformuivKHR GLuint program GLint location GLsizei bufSize GLuint *params void glGlobalAlphaFactorbSUN GLbyte factor void glGlobalAlphaFactordSUN GLdouble factor void glGlobalAlphaFactorfSUN GLfloat factor void glGlobalAlphaFactoriSUN GLint factor void glGlobalAlphaFactorsSUN GLshort factor void glGlobalAlphaFactorubSUN GLubyte factor void glGlobalAlphaFactoruiSUN GLuint factor void glGlobalAlphaFactorusSUN GLushort factor void glHint GLenum target GLenum mode void glHintPGI GLenum target GLint mode void glHistogram GLenum target GLsizei width GLenum internalformat GLboolean sink void glHistogramEXT GLenum target GLsizei width GLenum internalformat GLboolean sink void glIglooInterfaceSGIX GLenum pname const void *params void glImageTransformParameterfHP GLenum target GLenum pname GLfloat param void glImageTransformParameterfvHP GLenum target GLenum pname const GLfloat *params void glImageTransformParameteriHP GLenum target GLenum pname GLint param void glImageTransformParameterivHP GLenum target GLenum pname const GLint *params GLsync glImportSyncEXT GLenum external_sync_type GLintptr external_sync GLbitfield flags void glIndexFormatNV GLenum type GLsizei stride void glIndexFuncEXT GLenum func GLclampf ref void glIndexMask GLuint mask void glIndexMaterialEXT GLenum face GLenum mode void glIndexPointer GLenum type GLsizei stride const void *pointer void glIndexPointerEXT GLenum type GLsizei stride GLsizei count const void *pointer void glIndexPointerListIBM GLenum type GLint stride const void **pointer GLint ptrstride void glIndexd GLdouble c void glIndexdv const GLdouble *c void glIndexf GLfloat c void glIndexfv const GLfloat *c void glIndexi GLint c void glIndexiv const GLint *c void glIndexs GLshort c void glIndexsv const GLshort *c void glIndexub GLubyte c void glIndexubv const GLubyte *c void glIndexxOES GLfixed component void glIndexxvOES const GLfixed *component void glInitNames void glInsertComponentEXT GLuint res GLuint src GLuint num void glInsertEventMarkerEXT GLsizei length const GLchar *marker void glInstrumentsBufferSGIX GLsizei size GLint *buffer void glInterleavedArrays GLenum format GLsizei stride const void *pointer void glInterpolatePathsNV GLuint resultPath GLuint pathA GLuint pathB GLfloat weight void glInvalidateBufferData GLuint buffer void glInvalidateBufferSubData GLuint buffer GLintptr offset GLsizeiptr length void glInvalidateFramebuffer GLenum target GLsizei numAttachments const GLenum *attachments void glInvalidateNamedFramebufferData GLuint framebuffer GLsizei numAttachments const GLenum *attachments void glInvalidateNamedFramebufferSubData GLuint framebuffer GLsizei numAttachments const GLenum *attachments GLint x GLint y GLsizei width GLsizei height void glInvalidateSubFramebuffer GLenum target GLsizei numAttachments const GLenum *attachments GLint x GLint y GLsizei width GLsizei height void glInvalidateTexImage GLuint texture GLint level void glInvalidateTexSubImage GLuint texture GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLboolean glIsAsyncMarkerSGIX GLuint marker GLboolean glIsBuffer GLuint buffer GLboolean glIsBufferARB GLuint buffer GLboolean glIsBufferResidentNV GLenum target GLboolean glIsEnabled GLenum cap GLboolean glIsEnabledIndexedEXT GLenum target GLuint index GLboolean glIsEnabledi GLenum target GLuint index GLboolean glIsEnablediEXT GLenum target GLuint index GLboolean glIsEnablediNV GLenum target GLuint index GLboolean glIsFenceAPPLE GLuint fence GLboolean glIsFenceNV GLuint fence GLboolean glIsFramebuffer GLuint framebuffer GLboolean glIsFramebufferEXT GLuint framebuffer GLboolean glIsFramebufferOES GLuint framebuffer GLboolean glIsImageHandleResidentARB GLuint64 handle GLboolean glIsImageHandleResidentNV GLuint64 handle GLboolean glIsList GLuint list GLboolean glIsNameAMD GLenum identifier GLuint name GLboolean glIsNamedBufferResidentNV GLuint buffer GLboolean glIsNamedStringARB GLint namelen const GLchar *name GLboolean glIsObjectBufferATI GLuint buffer GLboolean glIsOcclusionQueryNV GLuint id GLboolean glIsPathNV GLuint path GLboolean glIsPointInFillPathNV GLuint path GLuint mask GLfloat x GLfloat y GLboolean glIsPointInStrokePathNV GLuint path GLfloat x GLfloat y GLboolean glIsProgram GLuint program GLboolean glIsProgramARB GLuint program GLboolean glIsProgramNV GLuint id GLboolean glIsProgramPipeline GLuint pipeline GLboolean glIsProgramPipelineEXT GLuint pipeline GLboolean glIsQuery GLuint id GLboolean glIsQueryARB GLuint id GLboolean glIsQueryEXT GLuint id GLboolean glIsRenderbuffer GLuint renderbuffer GLboolean glIsRenderbufferEXT GLuint renderbuffer GLboolean glIsRenderbufferOES GLuint renderbuffer GLboolean glIsSampler GLuint sampler GLboolean glIsShader GLuint shader GLboolean glIsSync GLsync sync GLboolean glIsSyncAPPLE GLsync sync GLboolean glIsTexture GLuint texture GLboolean glIsTextureEXT GLuint texture GLboolean glIsTextureHandleResidentARB GLuint64 handle GLboolean glIsTextureHandleResidentNV GLuint64 handle GLboolean glIsTransformFeedback GLuint id GLboolean glIsTransformFeedbackNV GLuint id GLboolean glIsVariantEnabledEXT GLuint id GLenum cap GLboolean glIsVertexArray GLuint array GLboolean glIsVertexArrayAPPLE GLuint array GLboolean glIsVertexArrayOES GLuint array GLboolean glIsVertexAttribEnabledAPPLE GLuint index GLenum pname void glLabelObjectEXT GLenum type GLuint object GLsizei length const GLchar *label void glLightEnviSGIX GLenum pname GLint param void glLightModelf GLenum pname GLfloat param void glLightModelfv GLenum pname const GLfloat *params void glLightModeli GLenum pname GLint param void glLightModeliv GLenum pname const GLint *params void glLightModelx GLenum pname GLfixed param void glLightModelxOES GLenum pname GLfixed param void glLightModelxv GLenum pname const GLfixed *param void glLightModelxvOES GLenum pname const GLfixed *param void glLightf GLenum light GLenum pname GLfloat param void glLightfv GLenum light GLenum pname const GLfloat *params void glLighti GLenum light GLenum pname GLint param void glLightiv GLenum light GLenum pname const GLint *params void glLightx GLenum light GLenum pname GLfixed param void glLightxOES GLenum light GLenum pname GLfixed param void glLightxv GLenum light GLenum pname const GLfixed *params void glLightxvOES GLenum light GLenum pname const GLfixed *params void glLineStipple GLint factor GLushort pattern void glLineWidth GLfloat width void glLineWidthx GLfixed width void glLineWidthxOES GLfixed width void glLinkProgram GLuint program void glLinkProgramARB GLhandleARB programObj void glListBase GLuint base void glListParameterfSGIX GLuint list GLenum pname GLfloat param void glListParameterfvSGIX GLuint list GLenum pname const GLfloat *params void glListParameteriSGIX GLuint list GLenum pname GLint param void glListParameterivSGIX GLuint list GLenum pname const GLint *params void glLoadIdentity void glLoadIdentityDeformationMapSGIX GLbitfield mask void glLoadMatrixd const GLdouble *m void glLoadMatrixf const GLfloat *m void glLoadMatrixx const GLfixed *m void glLoadMatrixxOES const GLfixed *m void glLoadName GLuint name void glLoadPaletteFromModelViewMatrixOES void glLoadProgramNV GLenum target GLuint id GLsizei len const GLubyte *program void glLoadTransposeMatrixd const GLdouble *m void glLoadTransposeMatrixdARB const GLdouble *m void glLoadTransposeMatrixf const GLfloat *m void glLoadTransposeMatrixfARB const GLfloat *m void glLoadTransposeMatrixxOES const GLfixed *m void glLockArraysEXT GLint first GLsizei count void glLogicOp GLenum opcode void glMakeBufferNonResidentNV GLenum target void glMakeBufferResidentNV GLenum target GLenum access void glMakeImageHandleNonResidentARB GLuint64 handle void glMakeImageHandleNonResidentNV GLuint64 handle void glMakeImageHandleResidentARB GLuint64 handle GLenum access void glMakeImageHandleResidentNV GLuint64 handle GLenum access void glMakeNamedBufferNonResidentNV GLuint buffer void glMakeNamedBufferResidentNV GLuint buffer GLenum access void glMakeTextureHandleNonResidentARB GLuint64 handle void glMakeTextureHandleNonResidentNV GLuint64 handle void glMakeTextureHandleResidentARB GLuint64 handle void glMakeTextureHandleResidentNV GLuint64 handle void glMap1d GLenum target GLdouble u1 GLdouble u2 GLint stride GLint order const GLdouble *points void glMap1f GLenum target GLfloat u1 GLfloat u2 GLint stride GLint order const GLfloat *points void glMap1xOES GLenum target GLfixed u1 GLfixed u2 GLint stride GLint order GLfixed points void glMap2d GLenum target GLdouble u1 GLdouble u2 GLint ustride GLint uorder GLdouble v1 GLdouble v2 GLint vstride GLint vorder const GLdouble *points void glMap2f GLenum target GLfloat u1 GLfloat u2 GLint ustride GLint uorder GLfloat v1 GLfloat v2 GLint vstride GLint vorder const GLfloat *points void glMap2xOES GLenum target GLfixed u1 GLfixed u2 GLint ustride GLint uorder GLfixed v1 GLfixed v2 GLint vstride GLint vorder GLfixed points void *glMapBuffer GLenum target GLenum access void *glMapBufferARB GLenum target GLenum access void *glMapBufferOES GLenum target GLenum access void *glMapBufferRange GLenum target GLintptr offset GLsizeiptr length GLbitfield access void *glMapBufferRangeEXT GLenum target GLintptr offset GLsizeiptr length GLbitfield access void glMapControlPointsNV GLenum target GLuint index GLenum type GLsizei ustride GLsizei vstride GLint uorder GLint vorder GLboolean packed const void *points void glMapGrid1d GLint un GLdouble u1 GLdouble u2 void glMapGrid1f GLint un GLfloat u1 GLfloat u2 void glMapGrid1xOES GLint n GLfixed u1 GLfixed u2 void glMapGrid2d GLint un GLdouble u1 GLdouble u2 GLint vn GLdouble v1 GLdouble v2 void glMapGrid2f GLint un GLfloat u1 GLfloat u2 GLint vn GLfloat v1 GLfloat v2 void glMapGrid2xOES GLint n GLfixed u1 GLfixed u2 GLfixed v1 GLfixed v2 void *glMapNamedBuffer GLuint buffer GLenum access void *glMapNamedBufferEXT GLuint buffer GLenum access void *glMapNamedBufferRange GLuint buffer GLintptr offset GLsizei length GLbitfield access void *glMapNamedBufferRangeEXT GLuint buffer GLintptr offset GLsizeiptr length GLbitfield access void *glMapObjectBufferATI GLuint buffer void glMapParameterfvNV GLenum target GLenum pname const GLfloat *params void glMapParameterivNV GLenum target GLenum pname const GLint *params void *glMapTexture2DINTEL GLuint texture GLint level GLbitfield access GLint *stride GLenum *layout void glMapVertexAttrib1dAPPLE GLuint index GLuint size GLdouble u1 GLdouble u2 GLint stride GLint order const GLdouble *points void glMapVertexAttrib1fAPPLE GLuint index GLuint size GLfloat u1 GLfloat u2 GLint stride GLint order const GLfloat *points void glMapVertexAttrib2dAPPLE GLuint index GLuint size GLdouble u1 GLdouble u2 GLint ustride GLint uorder GLdouble v1 GLdouble v2 GLint vstride GLint vorder const GLdouble *points void glMapVertexAttrib2fAPPLE GLuint index GLuint size GLfloat u1 GLfloat u2 GLint ustride GLint uorder GLfloat v1 GLfloat v2 GLint vstride GLint vorder const GLfloat *points void glMaterialf GLenum face GLenum pname GLfloat param void glMaterialfv GLenum face GLenum pname const GLfloat *params void glMateriali GLenum face GLenum pname GLint param void glMaterialiv GLenum face GLenum pname const GLint *params void glMaterialx GLenum face GLenum pname GLfixed param void glMaterialxOES GLenum face GLenum pname GLfixed param void glMaterialxv GLenum face GLenum pname const GLfixed *param void glMaterialxvOES GLenum face GLenum pname const GLfixed *param void glMatrixFrustumEXT GLenum mode GLdouble left GLdouble right GLdouble bottom GLdouble top GLdouble zNear GLdouble zFar void glMatrixIndexPointerARB GLint size GLenum type GLsizei stride const void *pointer void glMatrixIndexPointerOES GLint size GLenum type GLsizei stride const void *pointer void glMatrixIndexubvARB GLint size const GLubyte *indices void glMatrixIndexuivARB GLint size const GLuint *indices void glMatrixIndexusvARB GLint size const GLushort *indices void glMatrixLoad3x2fNV GLenum matrixMode const GLfloat *m void glMatrixLoad3x3fNV GLenum matrixMode const GLfloat *m void glMatrixLoadIdentityEXT GLenum mode void glMatrixLoadTranspose3x3fNV GLenum matrixMode const GLfloat *m void glMatrixLoadTransposedEXT GLenum mode const GLdouble *m void glMatrixLoadTransposefEXT GLenum mode const GLfloat *m void glMatrixLoaddEXT GLenum mode const GLdouble *m void glMatrixLoadfEXT GLenum mode const GLfloat *m void glMatrixMode GLenum mode void glMatrixMult3x2fNV GLenum matrixMode const GLfloat *m void glMatrixMult3x3fNV GLenum matrixMode const GLfloat *m void glMatrixMultTranspose3x3fNV GLenum matrixMode const GLfloat *m void glMatrixMultTransposedEXT GLenum mode const GLdouble *m void glMatrixMultTransposefEXT GLenum mode const GLfloat *m void glMatrixMultdEXT GLenum mode const GLdouble *m void glMatrixMultfEXT GLenum mode const GLfloat *m void glMatrixOrthoEXT GLenum mode GLdouble left GLdouble right GLdouble bottom GLdouble top GLdouble zNear GLdouble zFar void glMatrixPopEXT GLenum mode void glMatrixPushEXT GLenum mode void glMatrixRotatedEXT GLenum mode GLdouble angle GLdouble x GLdouble y GLdouble z void glMatrixRotatefEXT GLenum mode GLfloat angle GLfloat x GLfloat y GLfloat z void glMatrixScaledEXT GLenum mode GLdouble x GLdouble y GLdouble z void glMatrixScalefEXT GLenum mode GLfloat x GLfloat y GLfloat z void glMatrixTranslatedEXT GLenum mode GLdouble x GLdouble y GLdouble z void glMatrixTranslatefEXT GLenum mode GLfloat x GLfloat y GLfloat z void glMemoryBarrier GLbitfield barriers void glMemoryBarrierByRegion GLbitfield barriers void glMemoryBarrierEXT GLbitfield barriers void glMinSampleShading GLfloat value void glMinSampleShadingARB GLfloat value void glMinSampleShadingOES GLfloat value void glMinmax GLenum target GLenum internalformat GLboolean sink void glMinmaxEXT GLenum target GLenum internalformat GLboolean sink void glMultMatrixd const GLdouble *m void glMultMatrixf const GLfloat *m void glMultMatrixx const GLfixed *m void glMultMatrixxOES const GLfixed *m void glMultTransposeMatrixd const GLdouble *m void glMultTransposeMatrixdARB const GLdouble *m void glMultTransposeMatrixf const GLfloat *m void glMultTransposeMatrixfARB const GLfloat *m void glMultTransposeMatrixxOES const GLfixed *m void glMultiDrawArrays GLenum mode const GLint *first const GLsizei *count GLsizei drawcount void glMultiDrawArraysEXT GLenum mode const GLint *first const GLsizei *count GLsizei primcount void glMultiDrawArraysIndirect GLenum mode const void *indirect GLsizei drawcount GLsizei stride void glMultiDrawArraysIndirectAMD GLenum mode const void *indirect GLsizei primcount GLsizei stride void glMultiDrawArraysIndirectEXT GLenum mode const void *indirect GLsizei drawcount GLsizei stride void glMultiDrawArraysIndirectBindlessCountNV GLenum mode const void *indirect GLsizei drawCount GLsizei maxDrawCount GLsizei stride GLint vertexBufferCount void glMultiDrawArraysIndirectBindlessNV GLenum mode const void *indirect GLsizei drawCount GLsizei stride GLint vertexBufferCount void glMultiDrawArraysIndirectCountARB GLenum mode GLintptr indirect GLintptr drawcount GLsizei maxdrawcount GLsizei stride void glMultiDrawElementArrayAPPLE GLenum mode const GLint *first const GLsizei *count GLsizei primcount void glMultiDrawElements GLenum mode const GLsizei *count GLenum type const void *const*indices GLsizei drawcount void glMultiDrawElementsBaseVertex GLenum mode const GLsizei *count GLenum type const void *const*indices GLsizei drawcount const GLint *basevertex void glMultiDrawElementsBaseVertexEXT GLenum mode const GLsizei *count GLenum type const void *const*indices GLsizei primcount const GLint *basevertex void glMultiDrawElementsEXT GLenum mode const GLsizei *count GLenum type const void *const*indices GLsizei primcount void glMultiDrawElementsIndirect GLenum mode GLenum type const void *indirect GLsizei drawcount GLsizei stride void glMultiDrawElementsIndirectEXT GLenum mode GLenum type const void *indirect GLsizei drawcount GLsizei stride void glMultiDrawElementsIndirectAMD GLenum mode GLenum type const void *indirect GLsizei primcount GLsizei stride void glMultiDrawElementsIndirectBindlessCountNV GLenum mode GLenum type const void *indirect GLsizei drawCount GLsizei maxDrawCount GLsizei stride GLint vertexBufferCount void glMultiDrawElementsIndirectBindlessNV GLenum mode GLenum type const void *indirect GLsizei drawCount GLsizei stride GLint vertexBufferCount void glMultiDrawElementsIndirectCountARB GLenum mode GLenum type GLintptr indirect GLintptr drawcount GLsizei maxdrawcount GLsizei stride void glMultiDrawRangeElementArrayAPPLE GLenum mode GLuint start GLuint end const GLint *first const GLsizei *count GLsizei primcount void glMultiModeDrawArraysIBM const GLenum *mode const GLint *first const GLsizei *count GLsizei primcount GLint modestride void glMultiModeDrawElementsIBM const GLenum *mode const GLsizei *count GLenum type const void *const*indices GLsizei primcount GLint modestride void glMultiTexBufferEXT GLenum texunit GLenum target GLenum internalformat GLuint buffer void glMultiTexCoord1bOES GLenum texture GLbyte s void glMultiTexCoord1bvOES GLenum texture const GLbyte *coords void glMultiTexCoord1d GLenum target GLdouble s void glMultiTexCoord1dARB GLenum target GLdouble s void glMultiTexCoord1dv GLenum target const GLdouble *v void glMultiTexCoord1dvARB GLenum target const GLdouble *v void glMultiTexCoord1f GLenum target GLfloat s void glMultiTexCoord1fARB GLenum target GLfloat s void glMultiTexCoord1fv GLenum target const GLfloat *v void glMultiTexCoord1fvARB GLenum target const GLfloat *v void glMultiTexCoord1hNV GLenum target GLhalfNV s void glMultiTexCoord1hvNV GLenum target const GLhalfNV *v void glMultiTexCoord1i GLenum target GLint s void glMultiTexCoord1iARB GLenum target GLint s void glMultiTexCoord1iv GLenum target const GLint *v void glMultiTexCoord1ivARB GLenum target const GLint *v void glMultiTexCoord1s GLenum target GLshort s void glMultiTexCoord1sARB GLenum target GLshort s void glMultiTexCoord1sv GLenum target const GLshort *v void glMultiTexCoord1svARB GLenum target const GLshort *v void glMultiTexCoord1xOES GLenum texture GLfixed s void glMultiTexCoord1xvOES GLenum texture const GLfixed *coords void glMultiTexCoord2bOES GLenum texture GLbyte s GLbyte t void glMultiTexCoord2bvOES GLenum texture const GLbyte *coords void glMultiTexCoord2d GLenum target GLdouble s GLdouble t void glMultiTexCoord2dARB GLenum target GLdouble s GLdouble t void glMultiTexCoord2dv GLenum target const GLdouble *v void glMultiTexCoord2dvARB GLenum target const GLdouble *v void glMultiTexCoord2f GLenum target GLfloat s GLfloat t void glMultiTexCoord2fARB GLenum target GLfloat s GLfloat t void glMultiTexCoord2fv GLenum target const GLfloat *v void glMultiTexCoord2fvARB GLenum target const GLfloat *v void glMultiTexCoord2hNV GLenum target GLhalfNV s GLhalfNV t void glMultiTexCoord2hvNV GLenum target const GLhalfNV *v void glMultiTexCoord2i GLenum target GLint s GLint t void glMultiTexCoord2iARB GLenum target GLint s GLint t void glMultiTexCoord2iv GLenum target const GLint *v void glMultiTexCoord2ivARB GLenum target const GLint *v void glMultiTexCoord2s GLenum target GLshort s GLshort t void glMultiTexCoord2sARB GLenum target GLshort s GLshort t void glMultiTexCoord2sv GLenum target const GLshort *v void glMultiTexCoord2svARB GLenum target const GLshort *v void glMultiTexCoord2xOES GLenum texture GLfixed s GLfixed t void glMultiTexCoord2xvOES GLenum texture const GLfixed *coords void glMultiTexCoord3bOES GLenum texture GLbyte s GLbyte t GLbyte r void glMultiTexCoord3bvOES GLenum texture const GLbyte *coords void glMultiTexCoord3d GLenum target GLdouble s GLdouble t GLdouble r void glMultiTexCoord3dARB GLenum target GLdouble s GLdouble t GLdouble r void glMultiTexCoord3dv GLenum target const GLdouble *v void glMultiTexCoord3dvARB GLenum target const GLdouble *v void glMultiTexCoord3f GLenum target GLfloat s GLfloat t GLfloat r void glMultiTexCoord3fARB GLenum target GLfloat s GLfloat t GLfloat r void glMultiTexCoord3fv GLenum target const GLfloat *v void glMultiTexCoord3fvARB GLenum target const GLfloat *v void glMultiTexCoord3hNV GLenum target GLhalfNV s GLhalfNV t GLhalfNV r void glMultiTexCoord3hvNV GLenum target const GLhalfNV *v void glMultiTexCoord3i GLenum target GLint s GLint t GLint r void glMultiTexCoord3iARB GLenum target GLint s GLint t GLint r void glMultiTexCoord3iv GLenum target const GLint *v void glMultiTexCoord3ivARB GLenum target const GLint *v void glMultiTexCoord3s GLenum target GLshort s GLshort t GLshort r void glMultiTexCoord3sARB GLenum target GLshort s GLshort t GLshort r void glMultiTexCoord3sv GLenum target const GLshort *v void glMultiTexCoord3svARB GLenum target const GLshort *v void glMultiTexCoord3xOES GLenum texture GLfixed s GLfixed t GLfixed r void glMultiTexCoord3xvOES GLenum texture const GLfixed *coords void glMultiTexCoord4bOES GLenum texture GLbyte s GLbyte t GLbyte r GLbyte q void glMultiTexCoord4bvOES GLenum texture const GLbyte *coords void glMultiTexCoord4d GLenum target GLdouble s GLdouble t GLdouble r GLdouble q void glMultiTexCoord4dARB GLenum target GLdouble s GLdouble t GLdouble r GLdouble q void glMultiTexCoord4dv GLenum target const GLdouble *v void glMultiTexCoord4dvARB GLenum target const GLdouble *v void glMultiTexCoord4f GLenum target GLfloat s GLfloat t GLfloat r GLfloat q void glMultiTexCoord4fARB GLenum target GLfloat s GLfloat t GLfloat r GLfloat q void glMultiTexCoord4fv GLenum target const GLfloat *v void glMultiTexCoord4fvARB GLenum target const GLfloat *v void glMultiTexCoord4hNV GLenum target GLhalfNV s GLhalfNV t GLhalfNV r GLhalfNV q void glMultiTexCoord4hvNV GLenum target const GLhalfNV *v void glMultiTexCoord4i GLenum target GLint s GLint t GLint r GLint q void glMultiTexCoord4iARB GLenum target GLint s GLint t GLint r GLint q void glMultiTexCoord4iv GLenum target const GLint *v void glMultiTexCoord4ivARB GLenum target const GLint *v void glMultiTexCoord4s GLenum target GLshort s GLshort t GLshort r GLshort q void glMultiTexCoord4sARB GLenum target GLshort s GLshort t GLshort r GLshort q void glMultiTexCoord4sv GLenum target const GLshort *v void glMultiTexCoord4svARB GLenum target const GLshort *v void glMultiTexCoord4x GLenum texture GLfixed s GLfixed t GLfixed r GLfixed q void glMultiTexCoord4xOES GLenum texture GLfixed s GLfixed t GLfixed r GLfixed q void glMultiTexCoord4xvOES GLenum texture const GLfixed *coords void glMultiTexCoordP1ui GLenum texture GLenum type GLuint coords void glMultiTexCoordP1uiv GLenum texture GLenum type const GLuint *coords void glMultiTexCoordP2ui GLenum texture GLenum type GLuint coords void glMultiTexCoordP2uiv GLenum texture GLenum type const GLuint *coords void glMultiTexCoordP3ui GLenum texture GLenum type GLuint coords void glMultiTexCoordP3uiv GLenum texture GLenum type const GLuint *coords void glMultiTexCoordP4ui GLenum texture GLenum type GLuint coords void glMultiTexCoordP4uiv GLenum texture GLenum type const GLuint *coords void glMultiTexCoordPointerEXT GLenum texunit GLint size GLenum type GLsizei stride const void *pointer void glMultiTexEnvfEXT GLenum texunit GLenum target GLenum pname GLfloat param void glMultiTexEnvfvEXT GLenum texunit GLenum target GLenum pname const GLfloat *params void glMultiTexEnviEXT GLenum texunit GLenum target GLenum pname GLint param void glMultiTexEnvivEXT GLenum texunit GLenum target GLenum pname const GLint *params void glMultiTexGendEXT GLenum texunit GLenum coord GLenum pname GLdouble param void glMultiTexGendvEXT GLenum texunit GLenum coord GLenum pname const GLdouble *params void glMultiTexGenfEXT GLenum texunit GLenum coord GLenum pname GLfloat param void glMultiTexGenfvEXT GLenum texunit GLenum coord GLenum pname const GLfloat *params void glMultiTexGeniEXT GLenum texunit GLenum coord GLenum pname GLint param void glMultiTexGenivEXT GLenum texunit GLenum coord GLenum pname const GLint *params void glMultiTexImage1DEXT GLenum texunit GLenum target GLint level GLint internalformat GLsizei width GLint border GLenum format GLenum type const void *pixels void glMultiTexImage2DEXT GLenum texunit GLenum target GLint level GLint internalformat GLsizei width GLsizei height GLint border GLenum format GLenum type const void *pixels void glMultiTexImage3DEXT GLenum texunit GLenum target GLint level GLint internalformat GLsizei width GLsizei height GLsizei depth GLint border GLenum format GLenum type const void *pixels void glMultiTexParameterIivEXT GLenum texunit GLenum target GLenum pname const GLint *params void glMultiTexParameterIuivEXT GLenum texunit GLenum target GLenum pname const GLuint *params void glMultiTexParameterfEXT GLenum texunit GLenum target GLenum pname GLfloat param void glMultiTexParameterfvEXT GLenum texunit GLenum target GLenum pname const GLfloat *params void glMultiTexParameteriEXT GLenum texunit GLenum target GLenum pname GLint param void glMultiTexParameterivEXT GLenum texunit GLenum target GLenum pname const GLint *params void glMultiTexRenderbufferEXT GLenum texunit GLenum target GLuint renderbuffer void glMultiTexSubImage1DEXT GLenum texunit GLenum target GLint level GLint xoffset GLsizei width GLenum format GLenum type const void *pixels void glMultiTexSubImage2DEXT GLenum texunit GLenum target GLint level GLint xoffset GLint yoffset GLsizei width GLsizei height GLenum format GLenum type const void *pixels void glMultiTexSubImage3DEXT GLenum texunit GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLenum type const void *pixels void glNamedBufferData GLuint buffer GLsizei size const void *data GLenum usage void glNamedBufferDataEXT GLuint buffer GLsizeiptr size const void *data GLenum usage void glNamedBufferPageCommitmentARB GLuint buffer GLintptr offset GLsizeiptr size GLboolean commit void glNamedBufferPageCommitmentEXT GLuint buffer GLintptr offset GLsizeiptr size GLboolean commit void glNamedBufferStorage GLuint buffer GLsizei size const void *data GLbitfield flags void glNamedBufferStorageEXT GLuint buffer GLsizeiptr size const void *data GLbitfield flags void glNamedBufferSubData GLuint buffer GLintptr offset GLsizei size const void *data void glNamedBufferSubDataEXT GLuint buffer GLintptr offset GLsizeiptr size const void *data void glNamedCopyBufferSubDataEXT GLuint readBuffer GLuint writeBuffer GLintptr readOffset GLintptr writeOffset GLsizeiptr size void glNamedFramebufferDrawBuffer GLuint framebuffer GLenum buf void glNamedFramebufferDrawBuffers GLuint framebuffer GLsizei n const GLenum *bufs void glNamedFramebufferParameteri GLuint framebuffer GLenum pname GLint param void glNamedFramebufferParameteriEXT GLuint framebuffer GLenum pname GLint param void glNamedFramebufferReadBuffer GLuint framebuffer GLenum src void glNamedFramebufferRenderbuffer GLuint framebuffer GLenum attachment GLenum renderbuffertarget GLuint renderbuffer void glNamedFramebufferRenderbufferEXT GLuint framebuffer GLenum attachment GLenum renderbuffertarget GLuint renderbuffer void glNamedFramebufferTexture GLuint framebuffer GLenum attachment GLuint texture GLint level void glNamedFramebufferTexture1DEXT GLuint framebuffer GLenum attachment GLenum textarget GLuint texture GLint level void glNamedFramebufferTexture2DEXT GLuint framebuffer GLenum attachment GLenum textarget GLuint texture GLint level void glNamedFramebufferTexture3DEXT GLuint framebuffer GLenum attachment GLenum textarget GLuint texture GLint level GLint zoffset void glNamedFramebufferTextureEXT GLuint framebuffer GLenum attachment GLuint texture GLint level void glNamedFramebufferTextureFaceEXT GLuint framebuffer GLenum attachment GLuint texture GLint level GLenum face void glNamedFramebufferTextureLayer GLuint framebuffer GLenum attachment GLuint texture GLint level GLint layer void glNamedFramebufferTextureLayerEXT GLuint framebuffer GLenum attachment GLuint texture GLint level GLint layer void glNamedProgramLocalParameter4dEXT GLuint program GLenum target GLuint index GLdouble x GLdouble y GLdouble z GLdouble w void glNamedProgramLocalParameter4dvEXT GLuint program GLenum target GLuint index const GLdouble *params void glNamedProgramLocalParameter4fEXT GLuint program GLenum target GLuint index GLfloat x GLfloat y GLfloat z GLfloat w void glNamedProgramLocalParameter4fvEXT GLuint program GLenum target GLuint index const GLfloat *params void glNamedProgramLocalParameterI4iEXT GLuint program GLenum target GLuint index GLint x GLint y GLint z GLint w void glNamedProgramLocalParameterI4ivEXT GLuint program GLenum target GLuint index const GLint *params void glNamedProgramLocalParameterI4uiEXT GLuint program GLenum target GLuint index GLuint x GLuint y GLuint z GLuint w void glNamedProgramLocalParameterI4uivEXT GLuint program GLenum target GLuint index const GLuint *params void glNamedProgramLocalParameters4fvEXT GLuint program GLenum target GLuint index GLsizei count const GLfloat *params void glNamedProgramLocalParametersI4ivEXT GLuint program GLenum target GLuint index GLsizei count const GLint *params void glNamedProgramLocalParametersI4uivEXT GLuint program GLenum target GLuint index GLsizei count const GLuint *params void glNamedProgramStringEXT GLuint program GLenum target GLenum format GLsizei len const void *string void glNamedRenderbufferStorage GLuint renderbuffer GLenum internalformat GLsizei width GLsizei height void glNamedRenderbufferStorageEXT GLuint renderbuffer GLenum internalformat GLsizei width GLsizei height void glNamedRenderbufferStorageMultisample GLuint renderbuffer GLsizei samples GLenum internalformat GLsizei width GLsizei height void glNamedRenderbufferStorageMultisampleCoverageEXT GLuint renderbuffer GLsizei coverageSamples GLsizei colorSamples GLenum internalformat GLsizei width GLsizei height void glNamedRenderbufferStorageMultisampleEXT GLuint renderbuffer GLsizei samples GLenum internalformat GLsizei width GLsizei height void glNamedStringARB GLenum type GLint namelen const GLchar *name GLint stringlen const GLchar *string void glNewList GLuint list GLenum mode GLuint glNewObjectBufferATI GLsizei size const void *pointer GLenum usage void glNormal3b GLbyte nx GLbyte ny GLbyte nz void glNormal3bv const GLbyte *v void glNormal3d GLdouble nx GLdouble ny GLdouble nz void glNormal3dv const GLdouble *v void glNormal3f GLfloat nx GLfloat ny GLfloat nz void glNormal3fVertex3fSUN GLfloat nx GLfloat ny GLfloat nz GLfloat x GLfloat y GLfloat z void glNormal3fVertex3fvSUN const GLfloat *n const GLfloat *v void glNormal3fv const GLfloat *v void glNormal3hNV GLhalfNV nx GLhalfNV ny GLhalfNV nz void glNormal3hvNV const GLhalfNV *v void glNormal3i GLint nx GLint ny GLint nz void glNormal3iv const GLint *v void glNormal3s GLshort nx GLshort ny GLshort nz void glNormal3sv const GLshort *v void glNormal3x GLfixed nx GLfixed ny GLfixed nz void glNormal3xOES GLfixed nx GLfixed ny GLfixed nz void glNormal3xvOES const GLfixed *coords void glNormalFormatNV GLenum type GLsizei stride void glNormalP3ui GLenum type GLuint coords void glNormalP3uiv GLenum type const GLuint *coords void glNormalPointer GLenum type GLsizei stride const void *pointer void glNormalPointerEXT GLenum type GLsizei stride GLsizei count const void *pointer void glNormalPointerListIBM GLenum type GLint stride const void **pointer GLint ptrstride void glNormalPointervINTEL GLenum type const void **pointer void glNormalStream3bATI GLenum stream GLbyte nx GLbyte ny GLbyte nz void glNormalStream3bvATI GLenum stream const GLbyte *coords void glNormalStream3dATI GLenum stream GLdouble nx GLdouble ny GLdouble nz void glNormalStream3dvATI GLenum stream const GLdouble *coords void glNormalStream3fATI GLenum stream GLfloat nx GLfloat ny GLfloat nz void glNormalStream3fvATI GLenum stream const GLfloat *coords void glNormalStream3iATI GLenum stream GLint nx GLint ny GLint nz void glNormalStream3ivATI GLenum stream const GLint *coords void glNormalStream3sATI GLenum stream GLshort nx GLshort ny GLshort nz void glNormalStream3svATI GLenum stream const GLshort *coords void glObjectLabel GLenum identifier GLuint name GLsizei length const GLchar *label void glObjectLabelKHR GLenum identifier GLuint name GLsizei length const GLchar *label void glObjectPtrLabel const void *ptr GLsizei length const GLchar *label void glObjectPtrLabelKHR const void *ptr GLsizei length const GLchar *label GLenum glObjectPurgeableAPPLE GLenum objectType GLuint name GLenum option GLenum glObjectUnpurgeableAPPLE GLenum objectType GLuint name GLenum option void glOrtho GLdouble left GLdouble right GLdouble bottom GLdouble top GLdouble zNear GLdouble zFar void glOrthof GLfloat l GLfloat r GLfloat b GLfloat t GLfloat n GLfloat f void glOrthofOES GLfloat l GLfloat r GLfloat b GLfloat t GLfloat n GLfloat f void glOrthox GLfixed l GLfixed r GLfixed b GLfixed t GLfixed n GLfixed f void glOrthoxOES GLfixed l GLfixed r GLfixed b GLfixed t GLfixed n GLfixed f void glPNTrianglesfATI GLenum pname GLfloat param void glPNTrianglesiATI GLenum pname GLint param void glPassTexCoordATI GLuint dst GLuint coord GLenum swizzle void glPassThrough GLfloat token void glPassThroughxOES GLfixed token void glPatchParameterfv GLenum pname const GLfloat *values void glPatchParameteri GLenum pname GLint value void glPatchParameteriEXT GLenum pname GLint value void glPathColorGenNV GLenum color GLenum genMode GLenum colorFormat const GLfloat *coeffs void glPathCommandsNV GLuint path GLsizei numCommands const GLubyte *commands GLsizei numCoords GLenum coordType const void *coords void glPathCoordsNV GLuint path GLsizei numCoords GLenum coordType const void *coords void glPathCoverDepthFuncNV GLenum func void glPathDashArrayNV GLuint path GLsizei dashCount const GLfloat *dashArray void glPathFogGenNV GLenum genMode GLenum glPathGlyphIndexArrayNV GLuint firstPathName GLenum fontTarget const void *fontName GLbitfield fontStyle GLuint firstGlyphIndex GLsizei numGlyphs GLuint pathParameterTemplate GLfloat emScale GLenum glPathGlyphIndexRangeNV GLenum fontTarget const void *fontName GLbitfield fontStyle GLuint pathParameterTemplate GLfloat emScale GLuint baseAndCount[2] void glPathGlyphRangeNV GLuint firstPathName GLenum fontTarget const void *fontName GLbitfield fontStyle GLuint firstGlyph GLsizei numGlyphs GLenum handleMissingGlyphs GLuint pathParameterTemplate GLfloat emScale void glPathGlyphsNV GLuint firstPathName GLenum fontTarget const void *fontName GLbitfield fontStyle GLsizei numGlyphs GLenum type const void *charcodes GLenum handleMissingGlyphs GLuint pathParameterTemplate GLfloat emScale GLenum glPathMemoryGlyphIndexArrayNV GLuint firstPathName GLenum fontTarget GLsizeiptr fontSize const void *fontData GLsizei faceIndex GLuint firstGlyphIndex GLsizei numGlyphs GLuint pathParameterTemplate GLfloat emScale void glPathParameterfNV GLuint path GLenum pname GLfloat value void glPathParameterfvNV GLuint path GLenum pname const GLfloat *value void glPathParameteriNV GLuint path GLenum pname GLint value void glPathParameterivNV GLuint path GLenum pname const GLint *value void glPathStencilDepthOffsetNV GLfloat factor GLfloat units void glPathStencilFuncNV GLenum func GLint ref GLuint mask void glPathStringNV GLuint path GLenum format GLsizei length const void *pathString void glPathSubCommandsNV GLuint path GLsizei commandStart GLsizei commandsToDelete GLsizei numCommands const GLubyte *commands GLsizei numCoords GLenum coordType const void *coords void glPathSubCoordsNV GLuint path GLsizei coordStart GLsizei numCoords GLenum coordType const void *coords void glPathTexGenNV GLenum texCoordSet GLenum genMode GLint components const GLfloat *coeffs void glPauseTransformFeedback void glPauseTransformFeedbackNV void glPixelDataRangeNV GLenum target GLsizei length const void *pointer void glPixelMapfv GLenum map GLsizei mapsize const GLfloat *values void glPixelMapuiv GLenum map GLsizei mapsize const GLuint *values void glPixelMapusv GLenum map GLsizei mapsize const GLushort *values void glPixelMapx GLenum map GLint size const GLfixed *values void glPixelStoref GLenum pname GLfloat param void glPixelStorei GLenum pname GLint param void glPixelStorex GLenum pname GLfixed param void glPixelTexGenParameterfSGIS GLenum pname GLfloat param void glPixelTexGenParameterfvSGIS GLenum pname const GLfloat *params void glPixelTexGenParameteriSGIS GLenum pname GLint param void glPixelTexGenParameterivSGIS GLenum pname const GLint *params void glPixelTexGenSGIX GLenum mode void glPixelTransferf GLenum pname GLfloat param void glPixelTransferi GLenum pname GLint param void glPixelTransferxOES GLenum pname GLfixed param void glPixelTransformParameterfEXT GLenum target GLenum pname GLfloat param void glPixelTransformParameterfvEXT GLenum target GLenum pname const GLfloat *params void glPixelTransformParameteriEXT GLenum target GLenum pname GLint param void glPixelTransformParameterivEXT GLenum target GLenum pname const GLint *params void glPixelZoom GLfloat xfactor GLfloat yfactor void glPixelZoomxOES GLfixed xfactor GLfixed yfactor GLboolean glPointAlongPathNV GLuint path GLsizei startSegment GLsizei numSegments GLfloat distance GLfloat *x GLfloat *y GLfloat *tangentX GLfloat *tangentY void glPointParameterf GLenum pname GLfloat param void glPointParameterfARB GLenum pname GLfloat param void glPointParameterfEXT GLenum pname GLfloat param void glPointParameterfSGIS GLenum pname GLfloat param void glPointParameterfv GLenum pname const GLfloat *params void glPointParameterfvARB GLenum pname const GLfloat *params void glPointParameterfvEXT GLenum pname const GLfloat *params void glPointParameterfvSGIS GLenum pname const GLfloat *params void glPointParameteri GLenum pname GLint param void glPointParameteriNV GLenum pname GLint param void glPointParameteriv GLenum pname const GLint *params void glPointParameterivNV GLenum pname const GLint *params void glPointParameterx GLenum pname GLfixed param void glPointParameterxOES GLenum pname GLfixed param void glPointParameterxv GLenum pname const GLfixed *params void glPointParameterxvOES GLenum pname const GLfixed *params void glPointSize GLfloat size void glPointSizePointerOES GLenum type GLsizei stride const void *pointer void glPointSizex GLfixed size void glPointSizexOES GLfixed size GLint glPollAsyncSGIX GLuint *markerp GLint glPollInstrumentsSGIX GLint *marker_p void glPolygonMode GLenum face GLenum mode void glPolygonOffset GLfloat factor GLfloat units void glPolygonOffsetEXT GLfloat factor GLfloat bias void glPolygonOffsetx GLfixed factor GLfixed units void glPolygonOffsetxOES GLfixed factor GLfixed units void glPolygonOffsetClampEXT GLfloat factor GLfloat units GLfloat clamp void glPolygonStipple const GLubyte *mask void glPopAttrib void glPopClientAttrib void glPopDebugGroup void glPopDebugGroupKHR void glPopGroupMarkerEXT void glPopMatrix void glPopName void glPresentFrameDualFillNV GLuint video_slot GLuint64EXT minPresentTime GLuint beginPresentTimeId GLuint presentDurationId GLenum type GLenum target0 GLuint fill0 GLenum target1 GLuint fill1 GLenum target2 GLuint fill2 GLenum target3 GLuint fill3 void glPresentFrameKeyedNV GLuint video_slot GLuint64EXT minPresentTime GLuint beginPresentTimeId GLuint presentDurationId GLenum type GLenum target0 GLuint fill0 GLuint key0 GLenum target1 GLuint fill1 GLuint key1 void glPrimitiveBoundingBoxEXT GLfloat minX GLfloat minY GLfloat minZ GLfloat minW GLfloat maxX GLfloat maxY GLfloat maxZ GLfloat maxW void glPrimitiveRestartIndex GLuint index void glPrimitiveRestartIndexNV GLuint index void glPrimitiveRestartNV void glPrioritizeTextures GLsizei n const GLuint *textures const GLfloat *priorities void glPrioritizeTexturesEXT GLsizei n const GLuint *textures const GLclampf *priorities void glPrioritizeTexturesxOES GLsizei n const GLuint *textures const GLfixed *priorities void glProgramBinary GLuint program GLenum binaryFormat const void *binary GLsizei length void glProgramBinaryOES GLuint program GLenum binaryFormat const void *binary GLint length void glProgramBufferParametersIivNV GLenum target GLuint bindingIndex GLuint wordIndex GLsizei count const GLint *params void glProgramBufferParametersIuivNV GLenum target GLuint bindingIndex GLuint wordIndex GLsizei count const GLuint *params void glProgramBufferParametersfvNV GLenum target GLuint bindingIndex GLuint wordIndex GLsizei count const GLfloat *params void glProgramEnvParameter4dARB GLenum target GLuint index GLdouble x GLdouble y GLdouble z GLdouble w void glProgramEnvParameter4dvARB GLenum target GLuint index const GLdouble *params void glProgramEnvParameter4fARB GLenum target GLuint index GLfloat x GLfloat y GLfloat z GLfloat w void glProgramEnvParameter4fvARB GLenum target GLuint index const GLfloat *params void glProgramEnvParameterI4iNV GLenum target GLuint index GLint x GLint y GLint z GLint w void glProgramEnvParameterI4ivNV GLenum target GLuint index const GLint *params void glProgramEnvParameterI4uiNV GLenum target GLuint index GLuint x GLuint y GLuint z GLuint w void glProgramEnvParameterI4uivNV GLenum target GLuint index const GLuint *params void glProgramEnvParameters4fvEXT GLenum target GLuint index GLsizei count const GLfloat *params void glProgramEnvParametersI4ivNV GLenum target GLuint index GLsizei count const GLint *params void glProgramEnvParametersI4uivNV GLenum target GLuint index GLsizei count const GLuint *params void glProgramLocalParameter4dARB GLenum target GLuint index GLdouble x GLdouble y GLdouble z GLdouble w void glProgramLocalParameter4dvARB GLenum target GLuint index const GLdouble *params void glProgramLocalParameter4fARB GLenum target GLuint index GLfloat x GLfloat y GLfloat z GLfloat w void glProgramLocalParameter4fvARB GLenum target GLuint index const GLfloat *params void glProgramLocalParameterI4iNV GLenum target GLuint index GLint x GLint y GLint z GLint w void glProgramLocalParameterI4ivNV GLenum target GLuint index const GLint *params void glProgramLocalParameterI4uiNV GLenum target GLuint index GLuint x GLuint y GLuint z GLuint w void glProgramLocalParameterI4uivNV GLenum target GLuint index const GLuint *params void glProgramLocalParameters4fvEXT GLenum target GLuint index GLsizei count const GLfloat *params void glProgramLocalParametersI4ivNV GLenum target GLuint index GLsizei count const GLint *params void glProgramLocalParametersI4uivNV GLenum target GLuint index GLsizei count const GLuint *params void glProgramNamedParameter4dNV GLuint id GLsizei len const GLubyte *name GLdouble x GLdouble y GLdouble z GLdouble w void glProgramNamedParameter4dvNV GLuint id GLsizei len const GLubyte *name const GLdouble *v void glProgramNamedParameter4fNV GLuint id GLsizei len const GLubyte *name GLfloat x GLfloat y GLfloat z GLfloat w void glProgramNamedParameter4fvNV GLuint id GLsizei len const GLubyte *name const GLfloat *v void glProgramParameter4dNV GLenum target GLuint index GLdouble x GLdouble y GLdouble z GLdouble w void glProgramParameter4dvNV GLenum target GLuint index const GLdouble *v void glProgramParameter4fNV GLenum target GLuint index GLfloat x GLfloat y GLfloat z GLfloat w void glProgramParameter4fvNV GLenum target GLuint index const GLfloat *v void glProgramParameteri GLuint program GLenum pname GLint value void glProgramParameteriARB GLuint program GLenum pname GLint value void glProgramParameteriEXT GLuint program GLenum pname GLint value void glProgramParameters4dvNV GLenum target GLuint index GLsizei count const GLdouble *v void glProgramParameters4fvNV GLenum target GLuint index GLsizei count const GLfloat *v void glProgramPathFragmentInputGenNV GLuint program GLint location GLenum genMode GLint components const GLfloat *coeffs void glProgramStringARB GLenum target GLenum format GLsizei len const void *string void glProgramSubroutineParametersuivNV GLenum target GLsizei count const GLuint *params void glProgramUniform1d GLuint program GLint location GLdouble v0 void glProgramUniform1dEXT GLuint program GLint location GLdouble x void glProgramUniform1dv GLuint program GLint location GLsizei count const GLdouble *value void glProgramUniform1dvEXT GLuint program GLint location GLsizei count const GLdouble *value void glProgramUniform1f GLuint program GLint location GLfloat v0 void glProgramUniform1fEXT GLuint program GLint location GLfloat v0 void glProgramUniform1fv GLuint program GLint location GLsizei count const GLfloat *value void glProgramUniform1fvEXT GLuint program GLint location GLsizei count const GLfloat *value void glProgramUniform1i GLuint program GLint location GLint v0 void glProgramUniform1i64NV GLuint program GLint location GLint64EXT x void glProgramUniform1i64vNV GLuint program GLint location GLsizei count const GLint64EXT *value void glProgramUniform1iEXT GLuint program GLint location GLint v0 void glProgramUniform1iv GLuint program GLint location GLsizei count const GLint *value void glProgramUniform1ivEXT GLuint program GLint location GLsizei count const GLint *value void glProgramUniform1ui GLuint program GLint location GLuint v0 void glProgramUniform1ui64NV GLuint program GLint location GLuint64EXT x void glProgramUniform1ui64vNV GLuint program GLint location GLsizei count const GLuint64EXT *value void glProgramUniform1uiEXT GLuint program GLint location GLuint v0 void glProgramUniform1uiv GLuint program GLint location GLsizei count const GLuint *value void glProgramUniform1uivEXT GLuint program GLint location GLsizei count const GLuint *value void glProgramUniform2d GLuint program GLint location GLdouble v0 GLdouble v1 void glProgramUniform2dEXT GLuint program GLint location GLdouble x GLdouble y void glProgramUniform2dv GLuint program GLint location GLsizei count const GLdouble *value void glProgramUniform2dvEXT GLuint program GLint location GLsizei count const GLdouble *value void glProgramUniform2f GLuint program GLint location GLfloat v0 GLfloat v1 void glProgramUniform2fEXT GLuint program GLint location GLfloat v0 GLfloat v1 void glProgramUniform2fv GLuint program GLint location GLsizei count const GLfloat *value void glProgramUniform2fvEXT GLuint program GLint location GLsizei count const GLfloat *value void glProgramUniform2i GLuint program GLint location GLint v0 GLint v1 void glProgramUniform2i64NV GLuint program GLint location GLint64EXT x GLint64EXT y void glProgramUniform2i64vNV GLuint program GLint location GLsizei count const GLint64EXT *value void glProgramUniform2iEXT GLuint program GLint location GLint v0 GLint v1 void glProgramUniform2iv GLuint program GLint location GLsizei count const GLint *value void glProgramUniform2ivEXT GLuint program GLint location GLsizei count const GLint *value void glProgramUniform2ui GLuint program GLint location GLuint v0 GLuint v1 void glProgramUniform2ui64NV GLuint program GLint location GLuint64EXT x GLuint64EXT y void glProgramUniform2ui64vNV GLuint program GLint location GLsizei count const GLuint64EXT *value void glProgramUniform2uiEXT GLuint program GLint location GLuint v0 GLuint v1 void glProgramUniform2uiv GLuint program GLint location GLsizei count const GLuint *value void glProgramUniform2uivEXT GLuint program GLint location GLsizei count const GLuint *value void glProgramUniform3d GLuint program GLint location GLdouble v0 GLdouble v1 GLdouble v2 void glProgramUniform3dEXT GLuint program GLint location GLdouble x GLdouble y GLdouble z void glProgramUniform3dv GLuint program GLint location GLsizei count const GLdouble *value void glProgramUniform3dvEXT GLuint program GLint location GLsizei count const GLdouble *value void glProgramUniform3f GLuint program GLint location GLfloat v0 GLfloat v1 GLfloat v2 void glProgramUniform3fEXT GLuint program GLint location GLfloat v0 GLfloat v1 GLfloat v2 void glProgramUniform3fv GLuint program GLint location GLsizei count const GLfloat *value void glProgramUniform3fvEXT GLuint program GLint location GLsizei count const GLfloat *value void glProgramUniform3i GLuint program GLint location GLint v0 GLint v1 GLint v2 void glProgramUniform3i64NV GLuint program GLint location GLint64EXT x GLint64EXT y GLint64EXT z void glProgramUniform3i64vNV GLuint program GLint location GLsizei count const GLint64EXT *value void glProgramUniform3iEXT GLuint program GLint location GLint v0 GLint v1 GLint v2 void glProgramUniform3iv GLuint program GLint location GLsizei count const GLint *value void glProgramUniform3ivEXT GLuint program GLint location GLsizei count const GLint *value void glProgramUniform3ui GLuint program GLint location GLuint v0 GLuint v1 GLuint v2 void glProgramUniform3ui64NV GLuint program GLint location GLuint64EXT x GLuint64EXT y GLuint64EXT z void glProgramUniform3ui64vNV GLuint program GLint location GLsizei count const GLuint64EXT *value void glProgramUniform3uiEXT GLuint program GLint location GLuint v0 GLuint v1 GLuint v2 void glProgramUniform3uiv GLuint program GLint location GLsizei count const GLuint *value void glProgramUniform3uivEXT GLuint program GLint location GLsizei count const GLuint *value void glProgramUniform4d GLuint program GLint location GLdouble v0 GLdouble v1 GLdouble v2 GLdouble v3 void glProgramUniform4dEXT GLuint program GLint location GLdouble x GLdouble y GLdouble z GLdouble w void glProgramUniform4dv GLuint program GLint location GLsizei count const GLdouble *value void glProgramUniform4dvEXT GLuint program GLint location GLsizei count const GLdouble *value void glProgramUniform4f GLuint program GLint location GLfloat v0 GLfloat v1 GLfloat v2 GLfloat v3 void glProgramUniform4fEXT GLuint program GLint location GLfloat v0 GLfloat v1 GLfloat v2 GLfloat v3 void glProgramUniform4fv GLuint program GLint location GLsizei count const GLfloat *value void glProgramUniform4fvEXT GLuint program GLint location GLsizei count const GLfloat *value void glProgramUniform4i GLuint program GLint location GLint v0 GLint v1 GLint v2 GLint v3 void glProgramUniform4i64NV GLuint program GLint location GLint64EXT x GLint64EXT y GLint64EXT z GLint64EXT w void glProgramUniform4i64vNV GLuint program GLint location GLsizei count const GLint64EXT *value void glProgramUniform4iEXT GLuint program GLint location GLint v0 GLint v1 GLint v2 GLint v3 void glProgramUniform4iv GLuint program GLint location GLsizei count const GLint *value void glProgramUniform4ivEXT GLuint program GLint location GLsizei count const GLint *value void glProgramUniform4ui GLuint program GLint location GLuint v0 GLuint v1 GLuint v2 GLuint v3 void glProgramUniform4ui64NV GLuint program GLint location GLuint64EXT x GLuint64EXT y GLuint64EXT z GLuint64EXT w void glProgramUniform4ui64vNV GLuint program GLint location GLsizei count const GLuint64EXT *value void glProgramUniform4uiEXT GLuint program GLint location GLuint v0 GLuint v1 GLuint v2 GLuint v3 void glProgramUniform4uiv GLuint program GLint location GLsizei count const GLuint *value void glProgramUniform4uivEXT GLuint program GLint location GLsizei count const GLuint *value void glProgramUniformHandleui64ARB GLuint program GLint location GLuint64 value void glProgramUniformHandleui64NV GLuint program GLint location GLuint64 value void glProgramUniformHandleui64vARB GLuint program GLint location GLsizei count const GLuint64 *values void glProgramUniformHandleui64vNV GLuint program GLint location GLsizei count const GLuint64 *values void glProgramUniformMatrix2dv GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix2dvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix2fv GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix2fvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix2x3dv GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix2x3dvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix2x3fv GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix2x3fvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix2x4dv GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix2x4dvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix2x4fv GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix2x4fvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix3dv GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix3dvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix3fv GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix3fvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix3x2dv GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix3x2dvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix3x2fv GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix3x2fvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix3x4dv GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix3x4dvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix3x4fv GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix3x4fvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix4dv GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix4dvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix4fv GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix4fvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix4x2dv GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix4x2dvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix4x2fv GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix4x2fvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix4x3dv GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix4x3dvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLdouble *value void glProgramUniformMatrix4x3fv GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformMatrix4x3fvEXT GLuint program GLint location GLsizei count GLboolean transpose const GLfloat *value void glProgramUniformui64NV GLuint program GLint location GLuint64EXT value void glProgramUniformui64vNV GLuint program GLint location GLsizei count const GLuint64EXT *value void glProgramVertexLimitNV GLenum target GLint limit void glProvokingVertex GLenum mode void glProvokingVertexEXT GLenum mode void glPushAttrib GLbitfield mask void glPushClientAttrib GLbitfield mask void glPushClientAttribDefaultEXT GLbitfield mask void glPushDebugGroup GLenum source GLuint id GLsizei length const GLchar *message void glPushDebugGroupKHR GLenum source GLuint id GLsizei length const GLchar *message void glPushGroupMarkerEXT GLsizei length const GLchar *marker void glPushMatrix void glPushName GLuint name void glQueryCounter GLuint id GLenum target void glQueryCounterEXT GLuint id GLenum target GLbitfield glQueryMatrixxOES GLfixed *mantissa GLint *exponent void glQueryObjectParameteruiAMD GLenum target GLuint id GLenum pname GLuint param void glRasterPos2d GLdouble x GLdouble y void glRasterPos2dv const GLdouble *v void glRasterPos2f GLfloat x GLfloat y void glRasterPos2fv const GLfloat *v void glRasterPos2i GLint x GLint y void glRasterPos2iv const GLint *v void glRasterPos2s GLshort x GLshort y void glRasterPos2sv const GLshort *v void glRasterPos2xOES GLfixed x GLfixed y void glRasterPos2xvOES const GLfixed *coords void glRasterPos3d GLdouble x GLdouble y GLdouble z void glRasterPos3dv const GLdouble *v void glRasterPos3f GLfloat x GLfloat y GLfloat z void glRasterPos3fv const GLfloat *v void glRasterPos3i GLint x GLint y GLint z void glRasterPos3iv const GLint *v void glRasterPos3s GLshort x GLshort y GLshort z void glRasterPos3sv const GLshort *v void glRasterPos3xOES GLfixed x GLfixed y GLfixed z void glRasterPos3xvOES const GLfixed *coords void glRasterPos4d GLdouble x GLdouble y GLdouble z GLdouble w void glRasterPos4dv const GLdouble *v void glRasterPos4f GLfloat x GLfloat y GLfloat z GLfloat w void glRasterPos4fv const GLfloat *v void glRasterPos4i GLint x GLint y GLint z GLint w void glRasterPos4iv const GLint *v void glRasterPos4s GLshort x GLshort y GLshort z GLshort w void glRasterPos4sv const GLshort *v void glRasterPos4xOES GLfixed x GLfixed y GLfixed z GLfixed w void glRasterPos4xvOES const GLfixed *coords void glReadBuffer GLenum src void glReadBufferIndexedEXT GLenum src GLint index void glReadBufferNV GLenum mode void glReadInstrumentsSGIX GLint marker void glReadPixels GLint x GLint y GLsizei width GLsizei height GLenum format GLenum type void *pixels void glReadnPixels GLint x GLint y GLsizei width GLsizei height GLenum format GLenum type GLsizei bufSize void *data void glReadnPixelsARB GLint x GLint y GLsizei width GLsizei height GLenum format GLenum type GLsizei bufSize void *data void glReadnPixelsEXT GLint x GLint y GLsizei width GLsizei height GLenum format GLenum type GLsizei bufSize void *data void glReadnPixelsKHR GLint x GLint y GLsizei width GLsizei height GLenum format GLenum type GLsizei bufSize void *data void glRectd GLdouble x1 GLdouble y1 GLdouble x2 GLdouble y2 void glRectdv const GLdouble *v1 const GLdouble *v2 void glRectf GLfloat x1 GLfloat y1 GLfloat x2 GLfloat y2 void glRectfv const GLfloat *v1 const GLfloat *v2 void glRecti GLint x1 GLint y1 GLint x2 GLint y2 void glRectiv const GLint *v1 const GLint *v2 void glRects GLshort x1 GLshort y1 GLshort x2 GLshort y2 void glRectsv const GLshort *v1 const GLshort *v2 void glRectxOES GLfixed x1 GLfixed y1 GLfixed x2 GLfixed y2 void glRectxvOES const GLfixed *v1 const GLfixed *v2 void glReferencePlaneSGIX const GLdouble *equation void glReleaseShaderCompiler GLint glRenderMode GLenum mode void glRenderbufferStorage GLenum target GLenum internalformat GLsizei width GLsizei height void glRenderbufferStorageEXT GLenum target GLenum internalformat GLsizei width GLsizei height void glRenderbufferStorageMultisample GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height void glRenderbufferStorageMultisampleANGLE GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height void glRenderbufferStorageMultisampleAPPLE GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height void glRenderbufferStorageMultisampleCoverageNV GLenum target GLsizei coverageSamples GLsizei colorSamples GLenum internalformat GLsizei width GLsizei height void glRenderbufferStorageMultisampleEXT GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height void glRenderbufferStorageMultisampleIMG GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height void glRenderbufferStorageMultisampleNV GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height void glRenderbufferStorageOES GLenum target GLenum internalformat GLsizei width GLsizei height void glReplacementCodePointerSUN GLenum type GLsizei stride const void **pointer void glReplacementCodeubSUN GLubyte code void glReplacementCodeubvSUN const GLubyte *code void glReplacementCodeuiColor3fVertex3fSUN GLuint rc GLfloat r GLfloat g GLfloat b GLfloat x GLfloat y GLfloat z void glReplacementCodeuiColor3fVertex3fvSUN const GLuint *rc const GLfloat *c const GLfloat *v void glReplacementCodeuiColor4fNormal3fVertex3fSUN GLuint rc GLfloat r GLfloat g GLfloat b GLfloat a GLfloat nx GLfloat ny GLfloat nz GLfloat x GLfloat y GLfloat z void glReplacementCodeuiColor4fNormal3fVertex3fvSUN const GLuint *rc const GLfloat *c const GLfloat *n const GLfloat *v void glReplacementCodeuiColor4ubVertex3fSUN GLuint rc GLubyte r GLubyte g GLubyte b GLubyte a GLfloat x GLfloat y GLfloat z void glReplacementCodeuiColor4ubVertex3fvSUN const GLuint *rc const GLubyte *c const GLfloat *v void glReplacementCodeuiNormal3fVertex3fSUN GLuint rc GLfloat nx GLfloat ny GLfloat nz GLfloat x GLfloat y GLfloat z void glReplacementCodeuiNormal3fVertex3fvSUN const GLuint *rc const GLfloat *n const GLfloat *v void glReplacementCodeuiSUN GLuint code void glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN GLuint rc GLfloat s GLfloat t GLfloat r GLfloat g GLfloat b GLfloat a GLfloat nx GLfloat ny GLfloat nz GLfloat x GLfloat y GLfloat z void glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN const GLuint *rc const GLfloat *tc const GLfloat *c const GLfloat *n const GLfloat *v void glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN GLuint rc GLfloat s GLfloat t GLfloat nx GLfloat ny GLfloat nz GLfloat x GLfloat y GLfloat z void glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN const GLuint *rc const GLfloat *tc const GLfloat *n const GLfloat *v void glReplacementCodeuiTexCoord2fVertex3fSUN GLuint rc GLfloat s GLfloat t GLfloat x GLfloat y GLfloat z void glReplacementCodeuiTexCoord2fVertex3fvSUN const GLuint *rc const GLfloat *tc const GLfloat *v void glReplacementCodeuiVertex3fSUN GLuint rc GLfloat x GLfloat y GLfloat z void glReplacementCodeuiVertex3fvSUN const GLuint *rc const GLfloat *v void glReplacementCodeuivSUN const GLuint *code void glReplacementCodeusSUN GLushort code void glReplacementCodeusvSUN const GLushort *code void glRequestResidentProgramsNV GLsizei n const GLuint *programs void glResetHistogram GLenum target void glResetHistogramEXT GLenum target void glResetMinmax GLenum target void glResetMinmaxEXT GLenum target void glResizeBuffersMESA void glResolveMultisampleFramebufferAPPLE void glResumeTransformFeedback void glResumeTransformFeedbackNV void glRotated GLdouble angle GLdouble x GLdouble y GLdouble z void glRotatef GLfloat angle GLfloat x GLfloat y GLfloat z void glRotatex GLfixed angle GLfixed x GLfixed y GLfixed z void glRotatexOES GLfixed angle GLfixed x GLfixed y GLfixed z void glSampleCoverage GLfloat value GLboolean invert void glSampleCoverageARB GLfloat value GLboolean invert void glSampleCoverageOES GLfixed value GLboolean invert void glSampleCoveragex GLclampx value GLboolean invert void glSampleCoveragexOES GLclampx value GLboolean invert void glSampleMapATI GLuint dst GLuint interp GLenum swizzle void glSampleMaskEXT GLclampf value GLboolean invert void glSampleMaskIndexedNV GLuint index GLbitfield mask void glSampleMaskSGIS GLclampf value GLboolean invert void glSampleMaski GLuint maskNumber GLbitfield mask void glSamplePatternEXT GLenum pattern void glSamplePatternSGIS GLenum pattern void glSamplerParameterIiv GLuint sampler GLenum pname const GLint *param void glSamplerParameterIivEXT GLuint sampler GLenum pname const GLint *param void glSamplerParameterIuiv GLuint sampler GLenum pname const GLuint *param void glSamplerParameterIuivEXT GLuint sampler GLenum pname const GLuint *param void glSamplerParameterf GLuint sampler GLenum pname GLfloat param void glSamplerParameterfv GLuint sampler GLenum pname const GLfloat *param void glSamplerParameteri GLuint sampler GLenum pname GLint param void glSamplerParameteriv GLuint sampler GLenum pname const GLint *param void glScaled GLdouble x GLdouble y GLdouble z void glScalef GLfloat x GLfloat y GLfloat z void glScalex GLfixed x GLfixed y GLfixed z void glScalexOES GLfixed x GLfixed y GLfixed z void glScissor GLint x GLint y GLsizei width GLsizei height void glScissorArrayv GLuint first GLsizei count const GLint *v void glScissorArrayvNV GLuint first GLsizei count const GLint *v void glScissorIndexed GLuint index GLint left GLint bottom GLsizei width GLsizei height void glScissorIndexedNV GLuint index GLint left GLint bottom GLsizei width GLsizei height void glScissorIndexedv GLuint index const GLint *v void glScissorIndexedvNV GLuint index const GLint *v void glSecondaryColor3b GLbyte red GLbyte green GLbyte blue void glSecondaryColor3bEXT GLbyte red GLbyte green GLbyte blue void glSecondaryColor3bv const GLbyte *v void glSecondaryColor3bvEXT const GLbyte *v void glSecondaryColor3d GLdouble red GLdouble green GLdouble blue void glSecondaryColor3dEXT GLdouble red GLdouble green GLdouble blue void glSecondaryColor3dv const GLdouble *v void glSecondaryColor3dvEXT const GLdouble *v void glSecondaryColor3f GLfloat red GLfloat green GLfloat blue void glSecondaryColor3fEXT GLfloat red GLfloat green GLfloat blue void glSecondaryColor3fv const GLfloat *v void glSecondaryColor3fvEXT const GLfloat *v void glSecondaryColor3hNV GLhalfNV red GLhalfNV green GLhalfNV blue void glSecondaryColor3hvNV const GLhalfNV *v void glSecondaryColor3i GLint red GLint green GLint blue void glSecondaryColor3iEXT GLint red GLint green GLint blue void glSecondaryColor3iv const GLint *v void glSecondaryColor3ivEXT const GLint *v void glSecondaryColor3s GLshort red GLshort green GLshort blue void glSecondaryColor3sEXT GLshort red GLshort green GLshort blue void glSecondaryColor3sv const GLshort *v void glSecondaryColor3svEXT const GLshort *v void glSecondaryColor3ub GLubyte red GLubyte green GLubyte blue void glSecondaryColor3ubEXT GLubyte red GLubyte green GLubyte blue void glSecondaryColor3ubv const GLubyte *v void glSecondaryColor3ubvEXT const GLubyte *v void glSecondaryColor3ui GLuint red GLuint green GLuint blue void glSecondaryColor3uiEXT GLuint red GLuint green GLuint blue void glSecondaryColor3uiv const GLuint *v void glSecondaryColor3uivEXT const GLuint *v void glSecondaryColor3us GLushort red GLushort green GLushort blue void glSecondaryColor3usEXT GLushort red GLushort green GLushort blue void glSecondaryColor3usv const GLushort *v void glSecondaryColor3usvEXT const GLushort *v void glSecondaryColorFormatNV GLint size GLenum type GLsizei stride void glSecondaryColorP3ui GLenum type GLuint color void glSecondaryColorP3uiv GLenum type const GLuint *color void glSecondaryColorPointer GLint size GLenum type GLsizei stride const void *pointer void glSecondaryColorPointerEXT GLint size GLenum type GLsizei stride const void *pointer void glSecondaryColorPointerListIBM GLint size GLenum type GLint stride const void **pointer GLint ptrstride void glSelectBuffer GLsizei size GLuint *buffer void glSelectPerfMonitorCountersAMD GLuint monitor GLboolean enable GLuint group GLint numCounters GLuint *counterList void glSeparableFilter2D GLenum target GLenum internalformat GLsizei width GLsizei height GLenum format GLenum type const void *row const void *column void glSeparableFilter2DEXT GLenum target GLenum internalformat GLsizei width GLsizei height GLenum format GLenum type const void *row const void *column void glSetFenceAPPLE GLuint fence void glSetFenceNV GLuint fence GLenum condition void glSetFragmentShaderConstantATI GLuint dst const GLfloat *value void glSetInvariantEXT GLuint id GLenum type const void *addr void glSetLocalConstantEXT GLuint id GLenum type const void *addr void glSetMultisamplefvAMD GLenum pname GLuint index const GLfloat *val void glShadeModel GLenum mode void glShaderBinary GLsizei count const GLuint *shaders GLenum binaryformat const void *binary GLsizei length void glShaderOp1EXT GLenum op GLuint res GLuint arg1 void glShaderOp2EXT GLenum op GLuint res GLuint arg1 GLuint arg2 void glShaderOp3EXT GLenum op GLuint res GLuint arg1 GLuint arg2 GLuint arg3 void glShaderSource GLuint shader GLsizei count const GLchar *const*string const GLint *length void glShaderSourceARB GLhandleARB shaderObj GLsizei count const GLcharARB **string const GLint *length void glShaderStorageBlockBinding GLuint program GLuint storageBlockIndex GLuint storageBlockBinding void glSharpenTexFuncSGIS GLenum target GLsizei n const GLfloat *points void glSpriteParameterfSGIX GLenum pname GLfloat param void glSpriteParameterfvSGIX GLenum pname const GLfloat *params void glSpriteParameteriSGIX GLenum pname GLint param void glSpriteParameterivSGIX GLenum pname const GLint *params void glStartInstrumentsSGIX void glStartTilingQCOM GLuint x GLuint y GLuint width GLuint height GLbitfield preserveMask void glStencilClearTagEXT GLsizei stencilTagBits GLuint stencilClearTag void glStencilFillPathInstancedNV GLsizei numPaths GLenum pathNameType const void *paths GLuint pathBase GLenum fillMode GLuint mask GLenum transformType const GLfloat *transformValues void glStencilFillPathNV GLuint path GLenum fillMode GLuint mask void glStencilFunc GLenum func GLint ref GLuint mask void glStencilFuncSeparate GLenum face GLenum func GLint ref GLuint mask void glStencilFuncSeparateATI GLenum frontfunc GLenum backfunc GLint ref GLuint mask void glStencilMask GLuint mask void glStencilMaskSeparate GLenum face GLuint mask void glStencilOp GLenum fail GLenum zfail GLenum zpass void glStencilOpSeparate GLenum face GLenum sfail GLenum dpfail GLenum dppass void glStencilOpSeparateATI GLenum face GLenum sfail GLenum dpfail GLenum dppass void glStencilOpValueAMD GLenum face GLuint value void glStencilStrokePathInstancedNV GLsizei numPaths GLenum pathNameType const void *paths GLuint pathBase GLint reference GLuint mask GLenum transformType const GLfloat *transformValues void glStencilStrokePathNV GLuint path GLint reference GLuint mask void glStencilThenCoverFillPathInstancedNV GLsizei numPaths GLenum pathNameType const void *paths GLuint pathBase GLenum fillMode GLuint mask GLenum coverMode GLenum transformType const GLfloat *transformValues void glStencilThenCoverFillPathNV GLuint path GLenum fillMode GLuint mask GLenum coverMode void glStencilThenCoverStrokePathInstancedNV GLsizei numPaths GLenum pathNameType const void *paths GLuint pathBase GLint reference GLuint mask GLenum coverMode GLenum transformType const GLfloat *transformValues void glStencilThenCoverStrokePathNV GLuint path GLint reference GLuint mask GLenum coverMode void glStopInstrumentsSGIX GLint marker void glStringMarkerGREMEDY GLsizei len const void *string void glSwizzleEXT GLuint res GLuint in GLenum outX GLenum outY GLenum outZ GLenum outW void glSyncTextureINTEL GLuint texture void glTagSampleBufferSGIX void glTangent3bEXT GLbyte tx GLbyte ty GLbyte tz void glTangent3bvEXT const GLbyte *v void glTangent3dEXT GLdouble tx GLdouble ty GLdouble tz void glTangent3dvEXT const GLdouble *v void glTangent3fEXT GLfloat tx GLfloat ty GLfloat tz void glTangent3fvEXT const GLfloat *v void glTangent3iEXT GLint tx GLint ty GLint tz void glTangent3ivEXT const GLint *v void glTangent3sEXT GLshort tx GLshort ty GLshort tz void glTangent3svEXT const GLshort *v void glTangentPointerEXT GLenum type GLsizei stride const void *pointer void glTbufferMask3DFX GLuint mask void glTessellationFactorAMD GLfloat factor void glTessellationModeAMD GLenum mode GLboolean glTestFenceAPPLE GLuint fence GLboolean glTestFenceNV GLuint fence GLboolean glTestObjectAPPLE GLenum object GLuint name void glTexBuffer GLenum target GLenum internalformat GLuint buffer void glTexBufferARB GLenum target GLenum internalformat GLuint buffer void glTexBufferEXT GLenum target GLenum internalformat GLuint buffer void glTexBufferRange GLenum target GLenum internalformat GLuint buffer GLintptr offset GLsizeiptr size void glTexBufferRangeEXT GLenum target GLenum internalformat GLuint buffer GLintptr offset GLsizeiptr size void glTexBumpParameterfvATI GLenum pname const GLfloat *param void glTexBumpParameterivATI GLenum pname const GLint *param void glTexCoord1bOES GLbyte s void glTexCoord1bvOES const GLbyte *coords void glTexCoord1d GLdouble s void glTexCoord1dv const GLdouble *v void glTexCoord1f GLfloat s void glTexCoord1fv const GLfloat *v void glTexCoord1hNV GLhalfNV s void glTexCoord1hvNV const GLhalfNV *v void glTexCoord1i GLint s void glTexCoord1iv const GLint *v void glTexCoord1s GLshort s void glTexCoord1sv const GLshort *v void glTexCoord1xOES GLfixed s void glTexCoord1xvOES const GLfixed *coords void glTexCoord2bOES GLbyte s GLbyte t void glTexCoord2bvOES const GLbyte *coords void glTexCoord2d GLdouble s GLdouble t void glTexCoord2dv const GLdouble *v void glTexCoord2f GLfloat s GLfloat t void glTexCoord2fColor3fVertex3fSUN GLfloat s GLfloat t GLfloat r GLfloat g GLfloat b GLfloat x GLfloat y GLfloat z void glTexCoord2fColor3fVertex3fvSUN const GLfloat *tc const GLfloat *c const GLfloat *v void glTexCoord2fColor4fNormal3fVertex3fSUN GLfloat s GLfloat t GLfloat r GLfloat g GLfloat b GLfloat a GLfloat nx GLfloat ny GLfloat nz GLfloat x GLfloat y GLfloat z void glTexCoord2fColor4fNormal3fVertex3fvSUN const GLfloat *tc const GLfloat *c const GLfloat *n const GLfloat *v void glTexCoord2fColor4ubVertex3fSUN GLfloat s GLfloat t GLubyte r GLubyte g GLubyte b GLubyte a GLfloat x GLfloat y GLfloat z void glTexCoord2fColor4ubVertex3fvSUN const GLfloat *tc const GLubyte *c const GLfloat *v void glTexCoord2fNormal3fVertex3fSUN GLfloat s GLfloat t GLfloat nx GLfloat ny GLfloat nz GLfloat x GLfloat y GLfloat z void glTexCoord2fNormal3fVertex3fvSUN const GLfloat *tc const GLfloat *n const GLfloat *v void glTexCoord2fVertex3fSUN GLfloat s GLfloat t GLfloat x GLfloat y GLfloat z void glTexCoord2fVertex3fvSUN const GLfloat *tc const GLfloat *v void glTexCoord2fv const GLfloat *v void glTexCoord2hNV GLhalfNV s GLhalfNV t void glTexCoord2hvNV const GLhalfNV *v void glTexCoord2i GLint s GLint t void glTexCoord2iv const GLint *v void glTexCoord2s GLshort s GLshort t void glTexCoord2sv const GLshort *v void glTexCoord2xOES GLfixed s GLfixed t void glTexCoord2xvOES const GLfixed *coords void glTexCoord3bOES GLbyte s GLbyte t GLbyte r void glTexCoord3bvOES const GLbyte *coords void glTexCoord3d GLdouble s GLdouble t GLdouble r void glTexCoord3dv const GLdouble *v void glTexCoord3f GLfloat s GLfloat t GLfloat r void glTexCoord3fv const GLfloat *v void glTexCoord3hNV GLhalfNV s GLhalfNV t GLhalfNV r void glTexCoord3hvNV const GLhalfNV *v void glTexCoord3i GLint s GLint t GLint r void glTexCoord3iv const GLint *v void glTexCoord3s GLshort s GLshort t GLshort r void glTexCoord3sv const GLshort *v void glTexCoord3xOES GLfixed s GLfixed t GLfixed r void glTexCoord3xvOES const GLfixed *coords void glTexCoord4bOES GLbyte s GLbyte t GLbyte r GLbyte q void glTexCoord4bvOES const GLbyte *coords void glTexCoord4d GLdouble s GLdouble t GLdouble r GLdouble q void glTexCoord4dv const GLdouble *v void glTexCoord4f GLfloat s GLfloat t GLfloat r GLfloat q void glTexCoord4fColor4fNormal3fVertex4fSUN GLfloat s GLfloat t GLfloat p GLfloat q GLfloat r GLfloat g GLfloat b GLfloat a GLfloat nx GLfloat ny GLfloat nz GLfloat x GLfloat y GLfloat z GLfloat w void glTexCoord4fColor4fNormal3fVertex4fvSUN const GLfloat *tc const GLfloat *c const GLfloat *n const GLfloat *v void glTexCoord4fVertex4fSUN GLfloat s GLfloat t GLfloat p GLfloat q GLfloat x GLfloat y GLfloat z GLfloat w void glTexCoord4fVertex4fvSUN const GLfloat *tc const GLfloat *v void glTexCoord4fv const GLfloat *v void glTexCoord4hNV GLhalfNV s GLhalfNV t GLhalfNV r GLhalfNV q void glTexCoord4hvNV const GLhalfNV *v void glTexCoord4i GLint s GLint t GLint r GLint q void glTexCoord4iv const GLint *v void glTexCoord4s GLshort s GLshort t GLshort r GLshort q void glTexCoord4sv const GLshort *v void glTexCoord4xOES GLfixed s GLfixed t GLfixed r GLfixed q void glTexCoord4xvOES const GLfixed *coords void glTexCoordFormatNV GLint size GLenum type GLsizei stride void glTexCoordP1ui GLenum type GLuint coords void glTexCoordP1uiv GLenum type const GLuint *coords void glTexCoordP2ui GLenum type GLuint coords void glTexCoordP2uiv GLenum type const GLuint *coords void glTexCoordP3ui GLenum type GLuint coords void glTexCoordP3uiv GLenum type const GLuint *coords void glTexCoordP4ui GLenum type GLuint coords void glTexCoordP4uiv GLenum type const GLuint *coords void glTexCoordPointer GLint size GLenum type GLsizei stride const void *pointer void glTexCoordPointerEXT GLint size GLenum type GLsizei stride GLsizei count const void *pointer void glTexCoordPointerListIBM GLint size GLenum type GLint stride const void **pointer GLint ptrstride void glTexCoordPointervINTEL GLint size GLenum type const void **pointer void glTexEnvf GLenum target GLenum pname GLfloat param void glTexEnvfv GLenum target GLenum pname const GLfloat *params void glTexEnvi GLenum target GLenum pname GLint param void glTexEnviv GLenum target GLenum pname const GLint *params void glTexEnvx GLenum target GLenum pname GLfixed param void glTexEnvxOES GLenum target GLenum pname GLfixed param void glTexEnvxv GLenum target GLenum pname const GLfixed *params void glTexEnvxvOES GLenum target GLenum pname const GLfixed *params void glTexFilterFuncSGIS GLenum target GLenum filter GLsizei n const GLfloat *weights void glTexGend GLenum coord GLenum pname GLdouble param void glTexGendv GLenum coord GLenum pname const GLdouble *params void glTexGenf GLenum coord GLenum pname GLfloat param void glTexGenfOES GLenum coord GLenum pname GLfloat param void glTexGenfv GLenum coord GLenum pname const GLfloat *params void glTexGenfvOES GLenum coord GLenum pname const GLfloat *params void glTexGeni GLenum coord GLenum pname GLint param void glTexGeniOES GLenum coord GLenum pname GLint param void glTexGeniv GLenum coord GLenum pname const GLint *params void glTexGenivOES GLenum coord GLenum pname const GLint *params void glTexGenxOES GLenum coord GLenum pname GLfixed param void glTexGenxvOES GLenum coord GLenum pname const GLfixed *params void glTexImage1D GLenum target GLint level GLint internalformat GLsizei width GLint border GLenum format GLenum type const void *pixels void glTexImage2D GLenum target GLint level GLint internalformat GLsizei width GLsizei height GLint border GLenum format GLenum type const void *pixels void glTexImage2DMultisample GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height GLboolean fixedsamplelocations void glTexImage2DMultisampleCoverageNV GLenum target GLsizei coverageSamples GLsizei colorSamples GLint internalFormat GLsizei width GLsizei height GLboolean fixedSampleLocations void glTexImage3D GLenum target GLint level GLint internalformat GLsizei width GLsizei height GLsizei depth GLint border GLenum format GLenum type const void *pixels void glTexImage3DEXT GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLsizei depth GLint border GLenum format GLenum type const void *pixels void glTexImage3DMultisample GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height GLsizei depth GLboolean fixedsamplelocations void glTexImage3DMultisampleCoverageNV GLenum target GLsizei coverageSamples GLsizei colorSamples GLint internalFormat GLsizei width GLsizei height GLsizei depth GLboolean fixedSampleLocations void glTexImage3DOES GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLsizei depth GLint border GLenum format GLenum type const void *pixels void glTexImage4DSGIS GLenum target GLint level GLenum internalformat GLsizei width GLsizei height GLsizei depth GLsizei size4d GLint border GLenum format GLenum type const void *pixels void glTexPageCommitmentARB GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLboolean resident void glTexParameterIiv GLenum target GLenum pname const GLint *params void glTexParameterIivEXT GLenum target GLenum pname const GLint *params void glTexParameterIuiv GLenum target GLenum pname const GLuint *params void glTexParameterIuivEXT GLenum target GLenum pname const GLuint *params void glTexParameterf GLenum target GLenum pname GLfloat param void glTexParameterfv GLenum target GLenum pname const GLfloat *params void glTexParameteri GLenum target GLenum pname GLint param void glTexParameteriv GLenum target GLenum pname const GLint *params void glTexParameterx GLenum target GLenum pname GLfixed param void glTexParameterxOES GLenum target GLenum pname GLfixed param void glTexParameterxv GLenum target GLenum pname const GLfixed *params void glTexParameterxvOES GLenum target GLenum pname const GLfixed *params void glTexRenderbufferNV GLenum target GLuint renderbuffer void glTexStorage1D GLenum target GLsizei levels GLenum internalformat GLsizei width void glTexStorage1DEXT GLenum target GLsizei levels GLenum internalformat GLsizei width void glTexStorage2D GLenum target GLsizei levels GLenum internalformat GLsizei width GLsizei height void glTexStorage2DEXT GLenum target GLsizei levels GLenum internalformat GLsizei width GLsizei height void glTexStorage2DMultisample GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height GLboolean fixedsamplelocations void glTexStorage3D GLenum target GLsizei levels GLenum internalformat GLsizei width GLsizei height GLsizei depth void glTexStorage3DEXT GLenum target GLsizei levels GLenum internalformat GLsizei width GLsizei height GLsizei depth void glTexStorage3DMultisample GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height GLsizei depth GLboolean fixedsamplelocations void glTexStorage3DMultisampleOES GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height GLsizei depth GLboolean fixedsamplelocations void glTexStorageSparseAMD GLenum target GLenum internalFormat GLsizei width GLsizei height GLsizei depth GLsizei layers GLbitfield flags void glTexSubImage1D GLenum target GLint level GLint xoffset GLsizei width GLenum format GLenum type const void *pixels void glTexSubImage1DEXT GLenum target GLint level GLint xoffset GLsizei width GLenum format GLenum type const void *pixels void glTexSubImage2D GLenum target GLint level GLint xoffset GLint yoffset GLsizei width GLsizei height GLenum format GLenum type const void *pixels void glTexSubImage2DEXT GLenum target GLint level GLint xoffset GLint yoffset GLsizei width GLsizei height GLenum format GLenum type const void *pixels void glTexSubImage3D GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLenum type const void *pixels void glTexSubImage3DEXT GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLenum type const void *pixels void glTexSubImage3DOES GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLenum type const void *pixels void glTexSubImage4DSGIS GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLint woffset GLsizei width GLsizei height GLsizei depth GLsizei size4d GLenum format GLenum type const void *pixels void glTextureBarrier void glTextureBarrierNV void glTextureBuffer GLuint texture GLenum internalformat GLuint buffer void glTextureBufferEXT GLuint texture GLenum target GLenum internalformat GLuint buffer void glTextureBufferRange GLuint texture GLenum internalformat GLuint buffer GLintptr offset GLsizei size void glTextureBufferRangeEXT GLuint texture GLenum target GLenum internalformat GLuint buffer GLintptr offset GLsizeiptr size void glTextureColorMaskSGIS GLboolean red GLboolean green GLboolean blue GLboolean alpha void glTextureImage1DEXT GLuint texture GLenum target GLint level GLint internalformat GLsizei width GLint border GLenum format GLenum type const void *pixels void glTextureImage2DEXT GLuint texture GLenum target GLint level GLint internalformat GLsizei width GLsizei height GLint border GLenum format GLenum type const void *pixels void glTextureImage2DMultisampleCoverageNV GLuint texture GLenum target GLsizei coverageSamples GLsizei colorSamples GLint internalFormat GLsizei width GLsizei height GLboolean fixedSampleLocations void glTextureImage2DMultisampleNV GLuint texture GLenum target GLsizei samples GLint internalFormat GLsizei width GLsizei height GLboolean fixedSampleLocations void glTextureImage3DEXT GLuint texture GLenum target GLint level GLint internalformat GLsizei width GLsizei height GLsizei depth GLint border GLenum format GLenum type const void *pixels void glTextureImage3DMultisampleCoverageNV GLuint texture GLenum target GLsizei coverageSamples GLsizei colorSamples GLint internalFormat GLsizei width GLsizei height GLsizei depth GLboolean fixedSampleLocations void glTextureImage3DMultisampleNV GLuint texture GLenum target GLsizei samples GLint internalFormat GLsizei width GLsizei height GLsizei depth GLboolean fixedSampleLocations void glTextureLightEXT GLenum pname void glTextureMaterialEXT GLenum face GLenum mode void glTextureNormalEXT GLenum mode void glTexturePageCommitmentEXT GLuint texture GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLboolean resident void glTextureParameterIiv GLuint texture GLenum pname const GLint *params void glTextureParameterIivEXT GLuint texture GLenum target GLenum pname const GLint *params void glTextureParameterIuiv GLuint texture GLenum pname const GLuint *params void glTextureParameterIuivEXT GLuint texture GLenum target GLenum pname const GLuint *params void glTextureParameterf GLuint texture GLenum pname GLfloat param void glTextureParameterfEXT GLuint texture GLenum target GLenum pname GLfloat param void glTextureParameterfv GLuint texture GLenum pname const GLfloat *param void glTextureParameterfvEXT GLuint texture GLenum target GLenum pname const GLfloat *params void glTextureParameteri GLuint texture GLenum pname GLint param void glTextureParameteriEXT GLuint texture GLenum target GLenum pname GLint param void glTextureParameteriv GLuint texture GLenum pname const GLint *param void glTextureParameterivEXT GLuint texture GLenum target GLenum pname const GLint *params void glTextureRangeAPPLE GLenum target GLsizei length const void *pointer void glTextureRenderbufferEXT GLuint texture GLenum target GLuint renderbuffer void glTextureStorage1D GLuint texture GLsizei levels GLenum internalformat GLsizei width void glTextureStorage1DEXT GLuint texture GLenum target GLsizei levels GLenum internalformat GLsizei width void glTextureStorage2D GLuint texture GLsizei levels GLenum internalformat GLsizei width GLsizei height void glTextureStorage2DEXT GLuint texture GLenum target GLsizei levels GLenum internalformat GLsizei width GLsizei height void glTextureStorage2DMultisample GLuint texture GLsizei samples GLenum internalformat GLsizei width GLsizei height GLboolean fixedsamplelocations void glTextureStorage2DMultisampleEXT GLuint texture GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height GLboolean fixedsamplelocations void glTextureStorage3D GLuint texture GLsizei levels GLenum internalformat GLsizei width GLsizei height GLsizei depth void glTextureStorage3DEXT GLuint texture GLenum target GLsizei levels GLenum internalformat GLsizei width GLsizei height GLsizei depth void glTextureStorage3DMultisample GLuint texture GLsizei samples GLenum internalformat GLsizei width GLsizei height GLsizei depth GLboolean fixedsamplelocations void glTextureStorage3DMultisampleEXT GLuint texture GLenum target GLsizei samples GLenum internalformat GLsizei width GLsizei height GLsizei depth GLboolean fixedsamplelocations void glTextureStorageSparseAMD GLuint texture GLenum target GLenum internalFormat GLsizei width GLsizei height GLsizei depth GLsizei layers GLbitfield flags void glTextureSubImage1D GLuint texture GLint level GLint xoffset GLsizei width GLenum format GLenum type const void *pixels void glTextureSubImage1DEXT GLuint texture GLenum target GLint level GLint xoffset GLsizei width GLenum format GLenum type const void *pixels void glTextureSubImage2D GLuint texture GLint level GLint xoffset GLint yoffset GLsizei width GLsizei height GLenum format GLenum type const void *pixels void glTextureSubImage2DEXT GLuint texture GLenum target GLint level GLint xoffset GLint yoffset GLsizei width GLsizei height GLenum format GLenum type const void *pixels void glTextureSubImage3D GLuint texture GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLenum type const void *pixels void glTextureSubImage3DEXT GLuint texture GLenum target GLint level GLint xoffset GLint yoffset GLint zoffset GLsizei width GLsizei height GLsizei depth GLenum format GLenum type const void *pixels void glTextureView GLuint texture GLenum target GLuint origtexture GLenum internalformat GLuint minlevel GLuint numlevels GLuint minlayer GLuint numlayers void glTextureViewEXT GLuint texture GLenum target GLuint origtexture GLenum internalformat GLuint minlevel GLuint numlevels GLuint minlayer GLuint numlayers void glTrackMatrixNV GLenum target GLuint address GLenum matrix GLenum transform void glTransformFeedbackAttribsNV GLsizei count const GLint *attribs GLenum bufferMode void glTransformFeedbackBufferBase GLuint xfb GLuint index GLuint buffer void glTransformFeedbackBufferRange GLuint xfb GLuint index GLuint buffer GLintptr offset GLsizei size void glTransformFeedbackStreamAttribsNV GLsizei count const GLint *attribs GLsizei nbuffers const GLint *bufstreams GLenum bufferMode void glTransformFeedbackVaryings GLuint program GLsizei count const GLchar *const*varyings GLenum bufferMode void glTransformFeedbackVaryingsEXT GLuint program GLsizei count const GLchar *const*varyings GLenum bufferMode void glTransformFeedbackVaryingsNV GLuint program GLsizei count const GLint *locations GLenum bufferMode void glTransformPathNV GLuint resultPath GLuint srcPath GLenum transformType const GLfloat *transformValues void glTranslated GLdouble x GLdouble y GLdouble z void glTranslatef GLfloat x GLfloat y GLfloat z void glTranslatex GLfixed x GLfixed y GLfixed z void glTranslatexOES GLfixed x GLfixed y GLfixed z void glUniform1d GLint location GLdouble x void glUniform1dv GLint location GLsizei count const GLdouble *value void glUniform1f GLint location GLfloat v0 void glUniform1fARB GLint location GLfloat v0 void glUniform1fv GLint location GLsizei count const GLfloat *value void glUniform1fvARB GLint location GLsizei count const GLfloat *value void glUniform1i GLint location GLint v0 void glUniform1i64NV GLint location GLint64EXT x void glUniform1i64vNV GLint location GLsizei count const GLint64EXT *value void glUniform1iARB GLint location GLint v0 void glUniform1iv GLint location GLsizei count const GLint *value void glUniform1ivARB GLint location GLsizei count const GLint *value void glUniform1ui GLint location GLuint v0 void glUniform1ui64NV GLint location GLuint64EXT x void glUniform1ui64vNV GLint location GLsizei count const GLuint64EXT *value void glUniform1uiEXT GLint location GLuint v0 void glUniform1uiv GLint location GLsizei count const GLuint *value void glUniform1uivEXT GLint location GLsizei count const GLuint *value void glUniform2d GLint location GLdouble x GLdouble y void glUniform2dv GLint location GLsizei count const GLdouble *value void glUniform2f GLint location GLfloat v0 GLfloat v1 void glUniform2fARB GLint location GLfloat v0 GLfloat v1 void glUniform2fv GLint location GLsizei count const GLfloat *value void glUniform2fvARB GLint location GLsizei count const GLfloat *value void glUniform2i GLint location GLint v0 GLint v1 void glUniform2i64NV GLint location GLint64EXT x GLint64EXT y void glUniform2i64vNV GLint location GLsizei count const GLint64EXT *value void glUniform2iARB GLint location GLint v0 GLint v1 void glUniform2iv GLint location GLsizei count const GLint *value void glUniform2ivARB GLint location GLsizei count const GLint *value void glUniform2ui GLint location GLuint v0 GLuint v1 void glUniform2ui64NV GLint location GLuint64EXT x GLuint64EXT y void glUniform2ui64vNV GLint location GLsizei count const GLuint64EXT *value void glUniform2uiEXT GLint location GLuint v0 GLuint v1 void glUniform2uiv GLint location GLsizei count const GLuint *value void glUniform2uivEXT GLint location GLsizei count const GLuint *value void glUniform3d GLint location GLdouble x GLdouble y GLdouble z void glUniform3dv GLint location GLsizei count const GLdouble *value void glUniform3f GLint location GLfloat v0 GLfloat v1 GLfloat v2 void glUniform3fARB GLint location GLfloat v0 GLfloat v1 GLfloat v2 void glUniform3fv GLint location GLsizei count const GLfloat *value void glUniform3fvARB GLint location GLsizei count const GLfloat *value void glUniform3i GLint location GLint v0 GLint v1 GLint v2 void glUniform3i64NV GLint location GLint64EXT x GLint64EXT y GLint64EXT z void glUniform3i64vNV GLint location GLsizei count const GLint64EXT *value void glUniform3iARB GLint location GLint v0 GLint v1 GLint v2 void glUniform3iv GLint location GLsizei count const GLint *value void glUniform3ivARB GLint location GLsizei count const GLint *value void glUniform3ui GLint location GLuint v0 GLuint v1 GLuint v2 void glUniform3ui64NV GLint location GLuint64EXT x GLuint64EXT y GLuint64EXT z void glUniform3ui64vNV GLint location GLsizei count const GLuint64EXT *value void glUniform3uiEXT GLint location GLuint v0 GLuint v1 GLuint v2 void glUniform3uiv GLint location GLsizei count const GLuint *value void glUniform3uivEXT GLint location GLsizei count const GLuint *value void glUniform4d GLint location GLdouble x GLdouble y GLdouble z GLdouble w void glUniform4dv GLint location GLsizei count const GLdouble *value void glUniform4f GLint location GLfloat v0 GLfloat v1 GLfloat v2 GLfloat v3 void glUniform4fARB GLint location GLfloat v0 GLfloat v1 GLfloat v2 GLfloat v3 void glUniform4fv GLint location GLsizei count const GLfloat *value void glUniform4fvARB GLint location GLsizei count const GLfloat *value void glUniform4i GLint location GLint v0 GLint v1 GLint v2 GLint v3 void glUniform4i64NV GLint location GLint64EXT x GLint64EXT y GLint64EXT z GLint64EXT w void glUniform4i64vNV GLint location GLsizei count const GLint64EXT *value void glUniform4iARB GLint location GLint v0 GLint v1 GLint v2 GLint v3 void glUniform4iv GLint location GLsizei count const GLint *value void glUniform4ivARB GLint location GLsizei count const GLint *value void glUniform4ui GLint location GLuint v0 GLuint v1 GLuint v2 GLuint v3 void glUniform4ui64NV GLint location GLuint64EXT x GLuint64EXT y GLuint64EXT z GLuint64EXT w void glUniform4ui64vNV GLint location GLsizei count const GLuint64EXT *value void glUniform4uiEXT GLint location GLuint v0 GLuint v1 GLuint v2 GLuint v3 void glUniform4uiv GLint location GLsizei count const GLuint *value void glUniform4uivEXT GLint location GLsizei count const GLuint *value void glUniformBlockBinding GLuint program GLuint uniformBlockIndex GLuint uniformBlockBinding void glUniformBufferEXT GLuint program GLint location GLuint buffer void glUniformHandleui64ARB GLint location GLuint64 value void glUniformHandleui64NV GLint location GLuint64 value void glUniformHandleui64vARB GLint location GLsizei count const GLuint64 *value void glUniformHandleui64vNV GLint location GLsizei count const GLuint64 *value void glUniformMatrix2dv GLint location GLsizei count GLboolean transpose const GLdouble *value void glUniformMatrix2fv GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix2fvARB GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix2x3dv GLint location GLsizei count GLboolean transpose const GLdouble *value void glUniformMatrix2x3fv GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix2x3fvNV GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix2x4dv GLint location GLsizei count GLboolean transpose const GLdouble *value void glUniformMatrix2x4fv GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix2x4fvNV GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix3dv GLint location GLsizei count GLboolean transpose const GLdouble *value void glUniformMatrix3fv GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix3fvARB GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix3x2dv GLint location GLsizei count GLboolean transpose const GLdouble *value void glUniformMatrix3x2fv GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix3x2fvNV GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix3x4dv GLint location GLsizei count GLboolean transpose const GLdouble *value void glUniformMatrix3x4fv GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix3x4fvNV GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix4dv GLint location GLsizei count GLboolean transpose const GLdouble *value void glUniformMatrix4fv GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix4fvARB GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix4x2dv GLint location GLsizei count GLboolean transpose const GLdouble *value void glUniformMatrix4x2fv GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix4x2fvNV GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix4x3dv GLint location GLsizei count GLboolean transpose const GLdouble *value void glUniformMatrix4x3fv GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformMatrix4x3fvNV GLint location GLsizei count GLboolean transpose const GLfloat *value void glUniformSubroutinesuiv GLenum shadertype GLsizei count const GLuint *indices void glUniformui64NV GLint location GLuint64EXT value void glUniformui64vNV GLint location GLsizei count const GLuint64EXT *value void glUnlockArraysEXT GLboolean glUnmapBuffer GLenum target GLboolean glUnmapBufferARB GLenum target GLboolean glUnmapBufferOES GLenum target GLboolean glUnmapNamedBuffer GLuint buffer GLboolean glUnmapNamedBufferEXT GLuint buffer void glUnmapObjectBufferATI GLuint buffer void glUnmapTexture2DINTEL GLuint texture GLint level void glUpdateObjectBufferATI GLuint buffer GLuint offset GLsizei size const void *pointer GLenum preserve void glUseProgram GLuint program void glUseProgramObjectARB GLhandleARB programObj void glUseProgramStages GLuint pipeline GLbitfield stages GLuint program void glUseProgramStagesEXT GLuint pipeline GLbitfield stages GLuint program void glUseShaderProgramEXT GLenum type GLuint program void glVDPAUFiniNV void glVDPAUGetSurfaceivNV GLvdpauSurfaceNV surface GLenum pname GLsizei bufSize GLsizei *length GLint *values void glVDPAUInitNV const void *vdpDevice const void *getProcAddress GLboolean glVDPAUIsSurfaceNV GLvdpauSurfaceNV surface void glVDPAUMapSurfacesNV GLsizei numSurfaces const GLvdpauSurfaceNV *surfaces GLvdpauSurfaceNV glVDPAURegisterOutputSurfaceNV const void *vdpSurface GLenum target GLsizei numTextureNames const GLuint *textureNames GLvdpauSurfaceNV glVDPAURegisterVideoSurfaceNV const void *vdpSurface GLenum target GLsizei numTextureNames const GLuint *textureNames void glVDPAUSurfaceAccessNV GLvdpauSurfaceNV surface GLenum access void glVDPAUUnmapSurfacesNV GLsizei numSurface const GLvdpauSurfaceNV *surfaces void glVDPAUUnregisterSurfaceNV GLvdpauSurfaceNV surface void glValidateProgram GLuint program void glValidateProgramARB GLhandleARB programObj void glValidateProgramPipeline GLuint pipeline void glValidateProgramPipelineEXT GLuint pipeline void glVariantArrayObjectATI GLuint id GLenum type GLsizei stride GLuint buffer GLuint offset void glVariantPointerEXT GLuint id GLenum type GLuint stride const void *addr void glVariantbvEXT GLuint id const GLbyte *addr void glVariantdvEXT GLuint id const GLdouble *addr void glVariantfvEXT GLuint id const GLfloat *addr void glVariantivEXT GLuint id const GLint *addr void glVariantsvEXT GLuint id const GLshort *addr void glVariantubvEXT GLuint id const GLubyte *addr void glVariantuivEXT GLuint id const GLuint *addr void glVariantusvEXT GLuint id const GLushort *addr void glVertex2bOES GLbyte x GLbyte y void glVertex2bvOES const GLbyte *coords void glVertex2d GLdouble x GLdouble y void glVertex2dv const GLdouble *v void glVertex2f GLfloat x GLfloat y void glVertex2fv const GLfloat *v void glVertex2hNV GLhalfNV x GLhalfNV y void glVertex2hvNV const GLhalfNV *v void glVertex2i GLint x GLint y void glVertex2iv const GLint *v void glVertex2s GLshort x GLshort y void glVertex2sv const GLshort *v void glVertex2xOES GLfixed x void glVertex2xvOES const GLfixed *coords void glVertex3bOES GLbyte x GLbyte y GLbyte z void glVertex3bvOES const GLbyte *coords void glVertex3d GLdouble x GLdouble y GLdouble z void glVertex3dv const GLdouble *v void glVertex3f GLfloat x GLfloat y GLfloat z void glVertex3fv const GLfloat *v void glVertex3hNV GLhalfNV x GLhalfNV y GLhalfNV z void glVertex3hvNV const GLhalfNV *v void glVertex3i GLint x GLint y GLint z void glVertex3iv const GLint *v void glVertex3s GLshort x GLshort y GLshort z void glVertex3sv const GLshort *v void glVertex3xOES GLfixed x GLfixed y void glVertex3xvOES const GLfixed *coords void glVertex4bOES GLbyte x GLbyte y GLbyte z GLbyte w void glVertex4bvOES const GLbyte *coords void glVertex4d GLdouble x GLdouble y GLdouble z GLdouble w void glVertex4dv const GLdouble *v void glVertex4f GLfloat x GLfloat y GLfloat z GLfloat w void glVertex4fv const GLfloat *v void glVertex4hNV GLhalfNV x GLhalfNV y GLhalfNV z GLhalfNV w void glVertex4hvNV const GLhalfNV *v void glVertex4i GLint x GLint y GLint z GLint w void glVertex4iv const GLint *v void glVertex4s GLshort x GLshort y GLshort z GLshort w void glVertex4sv const GLshort *v void glVertex4xOES GLfixed x GLfixed y GLfixed z void glVertex4xvOES const GLfixed *coords void glVertexArrayAttribBinding GLuint vaobj GLuint attribindex GLuint bindingindex void glVertexArrayAttribFormat GLuint vaobj GLuint attribindex GLint size GLenum type GLboolean normalized GLuint relativeoffset void glVertexArrayAttribIFormat GLuint vaobj GLuint attribindex GLint size GLenum type GLuint relativeoffset void glVertexArrayAttribLFormat GLuint vaobj GLuint attribindex GLint size GLenum type GLuint relativeoffset void glVertexArrayBindVertexBufferEXT GLuint vaobj GLuint bindingindex GLuint buffer GLintptr offset GLsizei stride void glVertexArrayBindingDivisor GLuint vaobj GLuint bindingindex GLuint divisor void glVertexArrayColorOffsetEXT GLuint vaobj GLuint buffer GLint size GLenum type GLsizei stride GLintptr offset void glVertexArrayEdgeFlagOffsetEXT GLuint vaobj GLuint buffer GLsizei stride GLintptr offset void glVertexArrayElementBuffer GLuint vaobj GLuint buffer void glVertexArrayFogCoordOffsetEXT GLuint vaobj GLuint buffer GLenum type GLsizei stride GLintptr offset void glVertexArrayIndexOffsetEXT GLuint vaobj GLuint buffer GLenum type GLsizei stride GLintptr offset void glVertexArrayMultiTexCoordOffsetEXT GLuint vaobj GLuint buffer GLenum texunit GLint size GLenum type GLsizei stride GLintptr offset void glVertexArrayNormalOffsetEXT GLuint vaobj GLuint buffer GLenum type GLsizei stride GLintptr offset void glVertexArrayParameteriAPPLE GLenum pname GLint param void glVertexArrayRangeAPPLE GLsizei length void *pointer void glVertexArrayRangeNV GLsizei length const void *pointer void glVertexArraySecondaryColorOffsetEXT GLuint vaobj GLuint buffer GLint size GLenum type GLsizei stride GLintptr offset void glVertexArrayTexCoordOffsetEXT GLuint vaobj GLuint buffer GLint size GLenum type GLsizei stride GLintptr offset void glVertexArrayVertexAttribBindingEXT GLuint vaobj GLuint attribindex GLuint bindingindex void glVertexArrayVertexAttribDivisorEXT GLuint vaobj GLuint index GLuint divisor void glVertexArrayVertexAttribFormatEXT GLuint vaobj GLuint attribindex GLint size GLenum type GLboolean normalized GLuint relativeoffset void glVertexArrayVertexAttribIFormatEXT GLuint vaobj GLuint attribindex GLint size GLenum type GLuint relativeoffset void glVertexArrayVertexAttribIOffsetEXT GLuint vaobj GLuint buffer GLuint index GLint size GLenum type GLsizei stride GLintptr offset void glVertexArrayVertexAttribLFormatEXT GLuint vaobj GLuint attribindex GLint size GLenum type GLuint relativeoffset void glVertexArrayVertexAttribLOffsetEXT GLuint vaobj GLuint buffer GLuint index GLint size GLenum type GLsizei stride GLintptr offset void glVertexArrayVertexAttribOffsetEXT GLuint vaobj GLuint buffer GLuint index GLint size GLenum type GLboolean normalized GLsizei stride GLintptr offset void glVertexArrayVertexBindingDivisorEXT GLuint vaobj GLuint bindingindex GLuint divisor void glVertexArrayVertexBuffer GLuint vaobj GLuint bindingindex GLuint buffer GLintptr offset GLsizei stride void glVertexArrayVertexBuffers GLuint vaobj GLuint first GLsizei count const GLuint *buffers const GLintptr *offsets const GLsizei *strides void glVertexArrayVertexOffsetEXT GLuint vaobj GLuint buffer GLint size GLenum type GLsizei stride GLintptr offset void glVertexAttrib1d GLuint index GLdouble x void glVertexAttrib1dARB GLuint index GLdouble x void glVertexAttrib1dNV GLuint index GLdouble x void glVertexAttrib1dv GLuint index const GLdouble *v void glVertexAttrib1dvARB GLuint index const GLdouble *v void glVertexAttrib1dvNV GLuint index const GLdouble *v void glVertexAttrib1f GLuint index GLfloat x void glVertexAttrib1fARB GLuint index GLfloat x void glVertexAttrib1fNV GLuint index GLfloat x void glVertexAttrib1fv GLuint index const GLfloat *v void glVertexAttrib1fvARB GLuint index const GLfloat *v void glVertexAttrib1fvNV GLuint index const GLfloat *v void glVertexAttrib1hNV GLuint index GLhalfNV x void glVertexAttrib1hvNV GLuint index const GLhalfNV *v void glVertexAttrib1s GLuint index GLshort x void glVertexAttrib1sARB GLuint index GLshort x void glVertexAttrib1sNV GLuint index GLshort x void glVertexAttrib1sv GLuint index const GLshort *v void glVertexAttrib1svARB GLuint index const GLshort *v void glVertexAttrib1svNV GLuint index const GLshort *v void glVertexAttrib2d GLuint index GLdouble x GLdouble y void glVertexAttrib2dARB GLuint index GLdouble x GLdouble y void glVertexAttrib2dNV GLuint index GLdouble x GLdouble y void glVertexAttrib2dv GLuint index const GLdouble *v void glVertexAttrib2dvARB GLuint index const GLdouble *v void glVertexAttrib2dvNV GLuint index const GLdouble *v void glVertexAttrib2f GLuint index GLfloat x GLfloat y void glVertexAttrib2fARB GLuint index GLfloat x GLfloat y void glVertexAttrib2fNV GLuint index GLfloat x GLfloat y void glVertexAttrib2fv GLuint index const GLfloat *v void glVertexAttrib2fvARB GLuint index const GLfloat *v void glVertexAttrib2fvNV GLuint index const GLfloat *v void glVertexAttrib2hNV GLuint index GLhalfNV x GLhalfNV y void glVertexAttrib2hvNV GLuint index const GLhalfNV *v void glVertexAttrib2s GLuint index GLshort x GLshort y void glVertexAttrib2sARB GLuint index GLshort x GLshort y void glVertexAttrib2sNV GLuint index GLshort x GLshort y void glVertexAttrib2sv GLuint index const GLshort *v void glVertexAttrib2svARB GLuint index const GLshort *v void glVertexAttrib2svNV GLuint index const GLshort *v void glVertexAttrib3d GLuint index GLdouble x GLdouble y GLdouble z void glVertexAttrib3dARB GLuint index GLdouble x GLdouble y GLdouble z void glVertexAttrib3dNV GLuint index GLdouble x GLdouble y GLdouble z void glVertexAttrib3dv GLuint index const GLdouble *v void glVertexAttrib3dvARB GLuint index const GLdouble *v void glVertexAttrib3dvNV GLuint index const GLdouble *v void glVertexAttrib3f GLuint index GLfloat x GLfloat y GLfloat z void glVertexAttrib3fARB GLuint index GLfloat x GLfloat y GLfloat z void glVertexAttrib3fNV GLuint index GLfloat x GLfloat y GLfloat z void glVertexAttrib3fv GLuint index const GLfloat *v void glVertexAttrib3fvARB GLuint index const GLfloat *v void glVertexAttrib3fvNV GLuint index const GLfloat *v void glVertexAttrib3hNV GLuint index GLhalfNV x GLhalfNV y GLhalfNV z void glVertexAttrib3hvNV GLuint index const GLhalfNV *v void glVertexAttrib3s GLuint index GLshort x GLshort y GLshort z void glVertexAttrib3sARB GLuint index GLshort x GLshort y GLshort z void glVertexAttrib3sNV GLuint index GLshort x GLshort y GLshort z void glVertexAttrib3sv GLuint index const GLshort *v void glVertexAttrib3svARB GLuint index const GLshort *v void glVertexAttrib3svNV GLuint index const GLshort *v void glVertexAttrib4Nbv GLuint index const GLbyte *v void glVertexAttrib4NbvARB GLuint index const GLbyte *v void glVertexAttrib4Niv GLuint index const GLint *v void glVertexAttrib4NivARB GLuint index const GLint *v void glVertexAttrib4Nsv GLuint index const GLshort *v void glVertexAttrib4NsvARB GLuint index const GLshort *v void glVertexAttrib4Nub GLuint index GLubyte x GLubyte y GLubyte z GLubyte w void glVertexAttrib4NubARB GLuint index GLubyte x GLubyte y GLubyte z GLubyte w void glVertexAttrib4Nubv GLuint index const GLubyte *v void glVertexAttrib4NubvARB GLuint index const GLubyte *v void glVertexAttrib4Nuiv GLuint index const GLuint *v void glVertexAttrib4NuivARB GLuint index const GLuint *v void glVertexAttrib4Nusv GLuint index const GLushort *v void glVertexAttrib4NusvARB GLuint index const GLushort *v void glVertexAttrib4bv GLuint index const GLbyte *v void glVertexAttrib4bvARB GLuint index const GLbyte *v void glVertexAttrib4d GLuint index GLdouble x GLdouble y GLdouble z GLdouble w void glVertexAttrib4dARB GLuint index GLdouble x GLdouble y GLdouble z GLdouble w void glVertexAttrib4dNV GLuint index GLdouble x GLdouble y GLdouble z GLdouble w void glVertexAttrib4dv GLuint index const GLdouble *v void glVertexAttrib4dvARB GLuint index const GLdouble *v void glVertexAttrib4dvNV GLuint index const GLdouble *v void glVertexAttrib4f GLuint index GLfloat x GLfloat y GLfloat z GLfloat w void glVertexAttrib4fARB GLuint index GLfloat x GLfloat y GLfloat z GLfloat w void glVertexAttrib4fNV GLuint index GLfloat x GLfloat y GLfloat z GLfloat w void glVertexAttrib4fv GLuint index const GLfloat *v void glVertexAttrib4fvARB GLuint index const GLfloat *v void glVertexAttrib4fvNV GLuint index const GLfloat *v void glVertexAttrib4hNV GLuint index GLhalfNV x GLhalfNV y GLhalfNV z GLhalfNV w void glVertexAttrib4hvNV GLuint index const GLhalfNV *v void glVertexAttrib4iv GLuint index const GLint *v void glVertexAttrib4ivARB GLuint index const GLint *v void glVertexAttrib4s GLuint index GLshort x GLshort y GLshort z GLshort w void glVertexAttrib4sARB GLuint index GLshort x GLshort y GLshort z GLshort w void glVertexAttrib4sNV GLuint index GLshort x GLshort y GLshort z GLshort w void glVertexAttrib4sv GLuint index const GLshort *v void glVertexAttrib4svARB GLuint index const GLshort *v void glVertexAttrib4svNV GLuint index const GLshort *v void glVertexAttrib4ubNV GLuint index GLubyte x GLubyte y GLubyte z GLubyte w void glVertexAttrib4ubv GLuint index const GLubyte *v void glVertexAttrib4ubvARB GLuint index const GLubyte *v void glVertexAttrib4ubvNV GLuint index const GLubyte *v void glVertexAttrib4uiv GLuint index const GLuint *v void glVertexAttrib4uivARB GLuint index const GLuint *v void glVertexAttrib4usv GLuint index const GLushort *v void glVertexAttrib4usvARB GLuint index const GLushort *v void glVertexAttribArrayObjectATI GLuint index GLint size GLenum type GLboolean normalized GLsizei stride GLuint buffer GLuint offset void glVertexAttribBinding GLuint attribindex GLuint bindingindex void glVertexAttribDivisor GLuint index GLuint divisor void glVertexAttribDivisorANGLE GLuint index GLuint divisor void glVertexAttribDivisorARB GLuint index GLuint divisor void glVertexAttribDivisorEXT GLuint index GLuint divisor void glVertexAttribDivisorNV GLuint index GLuint divisor void glVertexAttribFormat GLuint attribindex GLint size GLenum type GLboolean normalized GLuint relativeoffset void glVertexAttribFormatNV GLuint index GLint size GLenum type GLboolean normalized GLsizei stride void glVertexAttribI1i GLuint index GLint x void glVertexAttribI1iEXT GLuint index GLint x void glVertexAttribI1iv GLuint index const GLint *v void glVertexAttribI1ivEXT GLuint index const GLint *v void glVertexAttribI1ui GLuint index GLuint x void glVertexAttribI1uiEXT GLuint index GLuint x void glVertexAttribI1uiv GLuint index const GLuint *v void glVertexAttribI1uivEXT GLuint index const GLuint *v void glVertexAttribI2i GLuint index GLint x GLint y void glVertexAttribI2iEXT GLuint index GLint x GLint y void glVertexAttribI2iv GLuint index const GLint *v void glVertexAttribI2ivEXT GLuint index const GLint *v void glVertexAttribI2ui GLuint index GLuint x GLuint y void glVertexAttribI2uiEXT GLuint index GLuint x GLuint y void glVertexAttribI2uiv GLuint index const GLuint *v void glVertexAttribI2uivEXT GLuint index const GLuint *v void glVertexAttribI3i GLuint index GLint x GLint y GLint z void glVertexAttribI3iEXT GLuint index GLint x GLint y GLint z void glVertexAttribI3iv GLuint index const GLint *v void glVertexAttribI3ivEXT GLuint index const GLint *v void glVertexAttribI3ui GLuint index GLuint x GLuint y GLuint z void glVertexAttribI3uiEXT GLuint index GLuint x GLuint y GLuint z void glVertexAttribI3uiv GLuint index const GLuint *v void glVertexAttribI3uivEXT GLuint index const GLuint *v void glVertexAttribI4bv GLuint index const GLbyte *v void glVertexAttribI4bvEXT GLuint index const GLbyte *v void glVertexAttribI4i GLuint index GLint x GLint y GLint z GLint w void glVertexAttribI4iEXT GLuint index GLint x GLint y GLint z GLint w void glVertexAttribI4iv GLuint index const GLint *v void glVertexAttribI4ivEXT GLuint index const GLint *v void glVertexAttribI4sv GLuint index const GLshort *v void glVertexAttribI4svEXT GLuint index const GLshort *v void glVertexAttribI4ubv GLuint index const GLubyte *v void glVertexAttribI4ubvEXT GLuint index const GLubyte *v void glVertexAttribI4ui GLuint index GLuint x GLuint y GLuint z GLuint w void glVertexAttribI4uiEXT GLuint index GLuint x GLuint y GLuint z GLuint w void glVertexAttribI4uiv GLuint index const GLuint *v void glVertexAttribI4uivEXT GLuint index const GLuint *v void glVertexAttribI4usv GLuint index const GLushort *v void glVertexAttribI4usvEXT GLuint index const GLushort *v void glVertexAttribIFormat GLuint attribindex GLint size GLenum type GLuint relativeoffset void glVertexAttribIFormatNV GLuint index GLint size GLenum type GLsizei stride void glVertexAttribIPointer GLuint index GLint size GLenum type GLsizei stride const void *pointer void glVertexAttribIPointerEXT GLuint index GLint size GLenum type GLsizei stride const void *pointer void glVertexAttribL1d GLuint index GLdouble x void glVertexAttribL1dEXT GLuint index GLdouble x void glVertexAttribL1dv GLuint index const GLdouble *v void glVertexAttribL1dvEXT GLuint index const GLdouble *v void glVertexAttribL1i64NV GLuint index GLint64EXT x void glVertexAttribL1i64vNV GLuint index const GLint64EXT *v void glVertexAttribL1ui64ARB GLuint index GLuint64EXT x void glVertexAttribL1ui64NV GLuint index GLuint64EXT x void glVertexAttribL1ui64vARB GLuint index const GLuint64EXT *v void glVertexAttribL1ui64vNV GLuint index const GLuint64EXT *v void glVertexAttribL2d GLuint index GLdouble x GLdouble y void glVertexAttribL2dEXT GLuint index GLdouble x GLdouble y void glVertexAttribL2dv GLuint index const GLdouble *v void glVertexAttribL2dvEXT GLuint index const GLdouble *v void glVertexAttribL2i64NV GLuint index GLint64EXT x GLint64EXT y void glVertexAttribL2i64vNV GLuint index const GLint64EXT *v void glVertexAttribL2ui64NV GLuint index GLuint64EXT x GLuint64EXT y void glVertexAttribL2ui64vNV GLuint index const GLuint64EXT *v void glVertexAttribL3d GLuint index GLdouble x GLdouble y GLdouble z void glVertexAttribL3dEXT GLuint index GLdouble x GLdouble y GLdouble z void glVertexAttribL3dv GLuint index const GLdouble *v void glVertexAttribL3dvEXT GLuint index const GLdouble *v void glVertexAttribL3i64NV GLuint index GLint64EXT x GLint64EXT y GLint64EXT z void glVertexAttribL3i64vNV GLuint index const GLint64EXT *v void glVertexAttribL3ui64NV GLuint index GLuint64EXT x GLuint64EXT y GLuint64EXT z void glVertexAttribL3ui64vNV GLuint index const GLuint64EXT *v void glVertexAttribL4d GLuint index GLdouble x GLdouble y GLdouble z GLdouble w void glVertexAttribL4dEXT GLuint index GLdouble x GLdouble y GLdouble z GLdouble w void glVertexAttribL4dv GLuint index const GLdouble *v void glVertexAttribL4dvEXT GLuint index const GLdouble *v void glVertexAttribL4i64NV GLuint index GLint64EXT x GLint64EXT y GLint64EXT z GLint64EXT w void glVertexAttribL4i64vNV GLuint index const GLint64EXT *v void glVertexAttribL4ui64NV GLuint index GLuint64EXT x GLuint64EXT y GLuint64EXT z GLuint64EXT w void glVertexAttribL4ui64vNV GLuint index const GLuint64EXT *v void glVertexAttribLFormat GLuint attribindex GLint size GLenum type GLuint relativeoffset void glVertexAttribLFormatNV GLuint index GLint size GLenum type GLsizei stride void glVertexAttribLPointer GLuint index GLint size GLenum type GLsizei stride const void *pointer void glVertexAttribLPointerEXT GLuint index GLint size GLenum type GLsizei stride const void *pointer void glVertexAttribP1ui GLuint index GLenum type GLboolean normalized GLuint value void glVertexAttribP1uiv GLuint index GLenum type GLboolean normalized const GLuint *value void glVertexAttribP2ui GLuint index GLenum type GLboolean normalized GLuint value void glVertexAttribP2uiv GLuint index GLenum type GLboolean normalized const GLuint *value void glVertexAttribP3ui GLuint index GLenum type GLboolean normalized GLuint value void glVertexAttribP3uiv GLuint index GLenum type GLboolean normalized const GLuint *value void glVertexAttribP4ui GLuint index GLenum type GLboolean normalized GLuint value void glVertexAttribP4uiv GLuint index GLenum type GLboolean normalized const GLuint *value void glVertexAttribParameteriAMD GLuint index GLenum pname GLint param void glVertexAttribPointer GLuint index GLint size GLenum type GLboolean normalized GLsizei stride const void *pointer void glVertexAttribPointerARB GLuint index GLint size GLenum type GLboolean normalized GLsizei stride const void *pointer void glVertexAttribPointerNV GLuint index GLint fsize GLenum type GLsizei stride const void *pointer void glVertexAttribs1dvNV GLuint index GLsizei count const GLdouble *v void glVertexAttribs1fvNV GLuint index GLsizei count const GLfloat *v void glVertexAttribs1hvNV GLuint index GLsizei n const GLhalfNV *v void glVertexAttribs1svNV GLuint index GLsizei count const GLshort *v void glVertexAttribs2dvNV GLuint index GLsizei count const GLdouble *v void glVertexAttribs2fvNV GLuint index GLsizei count const GLfloat *v void glVertexAttribs2hvNV GLuint index GLsizei n const GLhalfNV *v void glVertexAttribs2svNV GLuint index GLsizei count const GLshort *v void glVertexAttribs3dvNV GLuint index GLsizei count const GLdouble *v void glVertexAttribs3fvNV GLuint index GLsizei count const GLfloat *v void glVertexAttribs3hvNV GLuint index GLsizei n const GLhalfNV *v void glVertexAttribs3svNV GLuint index GLsizei count const GLshort *v void glVertexAttribs4dvNV GLuint index GLsizei count const GLdouble *v void glVertexAttribs4fvNV GLuint index GLsizei count const GLfloat *v void glVertexAttribs4hvNV GLuint index GLsizei n const GLhalfNV *v void glVertexAttribs4svNV GLuint index GLsizei count const GLshort *v void glVertexAttribs4ubvNV GLuint index GLsizei count const GLubyte *v void glVertexBindingDivisor GLuint bindingindex GLuint divisor void glVertexBlendARB GLint count void glVertexBlendEnvfATI GLenum pname GLfloat param void glVertexBlendEnviATI GLenum pname GLint param void glVertexFormatNV GLint size GLenum type GLsizei stride void glVertexP2ui GLenum type GLuint value void glVertexP2uiv GLenum type const GLuint *value void glVertexP3ui GLenum type GLuint value void glVertexP3uiv GLenum type const GLuint *value void glVertexP4ui GLenum type GLuint value void glVertexP4uiv GLenum type const GLuint *value void glVertexPointer GLint size GLenum type GLsizei stride const void *pointer void glVertexPointerEXT GLint size GLenum type GLsizei stride GLsizei count const void *pointer void glVertexPointerListIBM GLint size GLenum type GLint stride const void **pointer GLint ptrstride void glVertexPointervINTEL GLint size GLenum type const void **pointer void glVertexStream1dATI GLenum stream GLdouble x void glVertexStream1dvATI GLenum stream const GLdouble *coords void glVertexStream1fATI GLenum stream GLfloat x void glVertexStream1fvATI GLenum stream const GLfloat *coords void glVertexStream1iATI GLenum stream GLint x void glVertexStream1ivATI GLenum stream const GLint *coords void glVertexStream1sATI GLenum stream GLshort x void glVertexStream1svATI GLenum stream const GLshort *coords void glVertexStream2dATI GLenum stream GLdouble x GLdouble y void glVertexStream2dvATI GLenum stream const GLdouble *coords void glVertexStream2fATI GLenum stream GLfloat x GLfloat y void glVertexStream2fvATI GLenum stream const GLfloat *coords void glVertexStream2iATI GLenum stream GLint x GLint y void glVertexStream2ivATI GLenum stream const GLint *coords void glVertexStream2sATI GLenum stream GLshort x GLshort y void glVertexStream2svATI GLenum stream const GLshort *coords void glVertexStream3dATI GLenum stream GLdouble x GLdouble y GLdouble z void glVertexStream3dvATI GLenum stream const GLdouble *coords void glVertexStream3fATI GLenum stream GLfloat x GLfloat y GLfloat z void glVertexStream3fvATI GLenum stream const GLfloat *coords void glVertexStream3iATI GLenum stream GLint x GLint y GLint z void glVertexStream3ivATI GLenum stream const GLint *coords void glVertexStream3sATI GLenum stream GLshort x GLshort y GLshort z void glVertexStream3svATI GLenum stream const GLshort *coords void glVertexStream4dATI GLenum stream GLdouble x GLdouble y GLdouble z GLdouble w void glVertexStream4dvATI GLenum stream const GLdouble *coords void glVertexStream4fATI GLenum stream GLfloat x GLfloat y GLfloat z GLfloat w void glVertexStream4fvATI GLenum stream const GLfloat *coords void glVertexStream4iATI GLenum stream GLint x GLint y GLint z GLint w void glVertexStream4ivATI GLenum stream const GLint *coords void glVertexStream4sATI GLenum stream GLshort x GLshort y GLshort z GLshort w void glVertexStream4svATI GLenum stream const GLshort *coords void glVertexWeightPointerEXT GLint size GLenum type GLsizei stride const void *pointer void glVertexWeightfEXT GLfloat weight void glVertexWeightfvEXT const GLfloat *weight void glVertexWeighthNV GLhalfNV weight void glVertexWeighthvNV const GLhalfNV *weight GLenum glVideoCaptureNV GLuint video_capture_slot GLuint *sequence_num GLuint64EXT *capture_time void glVideoCaptureStreamParameterdvNV GLuint video_capture_slot GLuint stream GLenum pname const GLdouble *params void glVideoCaptureStreamParameterfvNV GLuint video_capture_slot GLuint stream GLenum pname const GLfloat *params void glVideoCaptureStreamParameterivNV GLuint video_capture_slot GLuint stream GLenum pname const GLint *params void glViewport GLint x GLint y GLsizei width GLsizei height void glViewportArrayv GLuint first GLsizei count const GLfloat *v void glViewportArrayvNV GLuint first GLsizei count const GLfloat *v void glViewportIndexedf GLuint index GLfloat x GLfloat y GLfloat w GLfloat h void glViewportIndexedfNV GLuint index GLfloat x GLfloat y GLfloat w GLfloat h void glViewportIndexedfv GLuint index const GLfloat *v void glViewportIndexedfvNV GLuint index const GLfloat *v void glWaitSync GLsync sync GLbitfield flags GLuint64 timeout void glWaitSyncAPPLE GLsync sync GLbitfield flags GLuint64 timeout void glWeightPathsNV GLuint resultPath GLsizei numPaths const GLuint *paths const GLfloat *weights void glWeightPointerARB GLint size GLenum type GLsizei stride const void *pointer void glWeightPointerOES GLint size GLenum type GLsizei stride const void *pointer void glWeightbvARB GLint size const GLbyte *weights void glWeightdvARB GLint size const GLdouble *weights void glWeightfvARB GLint size const GLfloat *weights void glWeightivARB GLint size const GLint *weights void glWeightsvARB GLint size const GLshort *weights void glWeightubvARB GLint size const GLubyte *weights void glWeightuivARB GLint size const GLuint *weights void glWeightusvARB GLint size const GLushort *weights void glWindowPos2d GLdouble x GLdouble y void glWindowPos2dARB GLdouble x GLdouble y void glWindowPos2dMESA GLdouble x GLdouble y void glWindowPos2dv const GLdouble *v void glWindowPos2dvARB const GLdouble *v void glWindowPos2dvMESA const GLdouble *v void glWindowPos2f GLfloat x GLfloat y void glWindowPos2fARB GLfloat x GLfloat y void glWindowPos2fMESA GLfloat x GLfloat y void glWindowPos2fv const GLfloat *v void glWindowPos2fvARB const GLfloat *v void glWindowPos2fvMESA const GLfloat *v void glWindowPos2i GLint x GLint y void glWindowPos2iARB GLint x GLint y void glWindowPos2iMESA GLint x GLint y void glWindowPos2iv const GLint *v void glWindowPos2ivARB const GLint *v void glWindowPos2ivMESA const GLint *v void glWindowPos2s GLshort x GLshort y void glWindowPos2sARB GLshort x GLshort y void glWindowPos2sMESA GLshort x GLshort y void glWindowPos2sv const GLshort *v void glWindowPos2svARB const GLshort *v void glWindowPos2svMESA const GLshort *v void glWindowPos3d GLdouble x GLdouble y GLdouble z void glWindowPos3dARB GLdouble x GLdouble y GLdouble z void glWindowPos3dMESA GLdouble x GLdouble y GLdouble z void glWindowPos3dv const GLdouble *v void glWindowPos3dvARB const GLdouble *v void glWindowPos3dvMESA const GLdouble *v void glWindowPos3f GLfloat x GLfloat y GLfloat z void glWindowPos3fARB GLfloat x GLfloat y GLfloat z void glWindowPos3fMESA GLfloat x GLfloat y GLfloat z void glWindowPos3fv const GLfloat *v void glWindowPos3fvARB const GLfloat *v void glWindowPos3fvMESA const GLfloat *v void glWindowPos3i GLint x GLint y GLint z void glWindowPos3iARB GLint x GLint y GLint z void glWindowPos3iMESA GLint x GLint y GLint z void glWindowPos3iv const GLint *v void glWindowPos3ivARB const GLint *v void glWindowPos3ivMESA const GLint *v void glWindowPos3s GLshort x GLshort y GLshort z void glWindowPos3sARB GLshort x GLshort y GLshort z void glWindowPos3sMESA GLshort x GLshort y GLshort z void glWindowPos3sv const GLshort *v void glWindowPos3svARB const GLshort *v void glWindowPos3svMESA const GLshort *v void glWindowPos4dMESA GLdouble x GLdouble y GLdouble z GLdouble w void glWindowPos4dvMESA const GLdouble *v void glWindowPos4fMESA GLfloat x GLfloat y GLfloat z GLfloat w void glWindowPos4fvMESA const GLfloat *v void glWindowPos4iMESA GLint x GLint y GLint z GLint w void glWindowPos4ivMESA const GLint *v void glWindowPos4sMESA GLshort x GLshort y GLshort z GLshort w void glWindowPos4svMESA const GLshort *v void glWriteMaskEXT GLuint res GLuint in GLenum outX GLenum outY GLenum outZ GLenum outW void glCoverageModulationNV GLenum components void glCoverageModulationTableNV GLsizei n const GLfloat *v void glFragmentCoverageColorNV GLuint color void glFramebufferSampleLocationsfvNV GLenum target GLuint start GLsizei count const GLfloat *v void glGetCoverageModulationTableNV GLsizei bufsize GLfloat *v void glNamedFramebufferSampleLocationsfvNV GLuint framebuffer GLuint start GLsizei count const GLfloat *v void glRasterSamplesEXT GLuint samples GLboolean fixedsamplelocations void glResolveDepthValuesNV void glSubpixelPrecisionBiasNV GLuint xbits GLuint ybits ================================================ FILE: server/registry/glx.xml ================================================ = 199901L #include #elif defined(__sun__) || defined(__digital__) #include #if defined(__STDC__) #if defined(__arch64__) || defined(_LP64) typedef long int int64_t; typedef unsigned long int uint64_t; #else typedef long long int int64_t; typedef unsigned long long int uint64_t; #endif /* __arch64__ */ #endif /* __STDC__ */ #elif defined( __VMS ) || defined(__sgi) #include #elif defined(__SCO__) || defined(__USLC__) #include #elif defined(__UNIXOS2__) || defined(__SOL64__) typedef long int int32_t; typedef long long int int64_t; typedef unsigned long long int uint64_t; #elif defined(_WIN32) && defined(__GNUC__) #include #elif defined(_WIN32) typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #else /* Fallback if nothing above works */ #include #endif #endif]]> typedef XID GLXFBConfigID; typedef struct __GLXFBConfigRec *GLXFBConfig; typedef XID GLXContextID; typedef struct __GLXcontextRec *GLXContext; typedef XID GLXPixmap; typedef XID GLXDrawable; typedef XID GLXWindow; typedef XID GLXPbuffer; typedef void ( *__GLXextFuncPtr)(void); typedef XID GLXVideoCaptureDeviceNV; typedef unsigned int GLXVideoDeviceNV; typedef XID GLXVideoSourceSGIX; typedef XID GLXFBConfigIDSGIX; typedef struct __GLXFBConfigRec *GLXFBConfigSGIX; typedef XID GLXPbufferSGIX; typedef struct { int event_type; /* GLX_DAMAGED or GLX_SAVED */ int draw_type; /* GLX_WINDOW or GLX_PBUFFER */ unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came for SendEvent request */ Display *display; /* display the event was read from */ GLXDrawable drawable; /* XID of Drawable */ unsigned int buffer_mask; /* mask indicating which buffers are affected */ unsigned int aux_buffer; /* which aux buffer was affected */ int x, y; int width, height; int count; /* if nonzero, at least this many more */ } GLXPbufferClobberEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ GLXDrawable drawable; /* drawable on which event was requested in event mask */ int event_type; int64_t ust; int64_t msc; int64_t sbc; } GLXBufferSwapComplete; typedef union __GLXEvent { GLXPbufferClobberEvent glxpbufferclobber; GLXBufferSwapComplete glxbufferswapcomplete; long pad[24]; } GLXEvent; typedef struct { int type; unsigned long serial; Bool send_event; Display *display; int extension; int evtype; GLXDrawable window; Bool stereo_tree; } GLXStereoNotifyEventEXT; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came for SendEvent request */ Display *display; /* display the event was read from */ GLXDrawable drawable; /* i.d. of Drawable */ int event_type; /* GLX_DAMAGED_SGIX or GLX_SAVED_SGIX */ int draw_type; /* GLX_WINDOW_SGIX or GLX_PBUFFER_SGIX */ unsigned int mask; /* mask indicating which buffers are affected*/ int x, y; int width, height; int count; /* if nonzero, at least this many more */ } GLXBufferClobberEventSGIX; typedef struct { char pipeName[80]; /* Should be [GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX] */ int networkId; } GLXHyperpipeNetworkSGIX; typedef struct { char pipeName[80]; /* Should be [GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX] */ int channel; unsigned int participationType; int timeSlice; } GLXHyperpipeConfigSGIX; typedef struct { char pipeName[80]; /* Should be [GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX] */ int srcXOrigin, srcYOrigin, srcWidth, srcHeight; int destXOrigin, destYOrigin, destWidth, destHeight; } GLXPipeRect; typedef struct { char pipeName[80]; /* Should be [GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX] */ int XOrigin, YOrigin, maxHeight, maxWidth; } GLXPipeRectLimits; Bool glXAssociateDMPbufferSGIX Display *dpy GLXPbufferSGIX pbuffer DMparams *params DMbuffer dmbuffer int glXBindChannelToWindowSGIX Display *display int screen int channel Window window int glXBindHyperpipeSGIX Display *dpy int hpId Bool glXBindSwapBarrierNV Display *dpy GLuint group GLuint barrier void glXBindSwapBarrierSGIX Display *dpy GLXDrawable drawable int barrier void glXBindTexImageEXT Display *dpy GLXDrawable drawable int buffer const int *attrib_list int glXBindVideoCaptureDeviceNV Display *dpy unsigned int video_capture_slot GLXVideoCaptureDeviceNV device int glXBindVideoDeviceNV Display *dpy unsigned int video_slot unsigned int video_device const int *attrib_list int glXBindVideoImageNV Display *dpy GLXVideoDeviceNV VideoDevice GLXPbuffer pbuf int iVideoBuffer void glXBlitContextFramebufferAMD GLXContext dstCtx GLint srcX0 GLint srcY0 GLint srcX1 GLint srcY1 GLint dstX0 GLint dstY0 GLint dstX1 GLint dstY1 GLbitfield mask GLenum filter int glXChannelRectSGIX Display *display int screen int channel int x int y int w int h int glXChannelRectSyncSGIX Display *display int screen int channel GLenum synctype GLXFBConfig *glXChooseFBConfig Display *dpy int screen const int *attrib_list int *nelements GLXFBConfigSGIX *glXChooseFBConfigSGIX Display *dpy int screen int *attrib_list int *nelements XVisualInfo *glXChooseVisual Display *dpy int screen int *attribList void glXCopyBufferSubDataNV Display *dpy GLXContext readCtx GLXContext writeCtx GLenum readTarget GLenum writeTarget GLintptr readOffset GLintptr writeOffset GLsizeiptr size void glXNamedCopyBufferSubDataNV Display *dpy GLXContext readCtx GLXContext writeCtx GLuint readBuffer GLuint writeBuffer GLintptr readOffset GLintptr writeOffset GLsizeiptr size void glXCopyContext Display *dpy GLXContext src GLXContext dst unsigned long mask void glXCopyImageSubDataNV Display *dpy GLXContext srcCtx GLuint srcName GLenum srcTarget GLint srcLevel GLint srcX GLint srcY GLint srcZ GLXContext dstCtx GLuint dstName GLenum dstTarget GLint dstLevel GLint dstX GLint dstY GLint dstZ GLsizei width GLsizei height GLsizei depth void glXCopySubBufferMESA Display *dpy GLXDrawable drawable int x int y int width int height GLXContext glXCreateAssociatedContextAMD unsigned int id GLXContext share_list GLXContext glXCreateAssociatedContextAttribsAMD unsigned int id GLXContext share_context const int *attribList GLXContext glXCreateContextAttribsARB Display *dpy GLXFBConfig config GLXContext share_context Bool direct const int *attrib_list GLXContext glXCreateContext Display *dpy XVisualInfo *vis GLXContext shareList Bool direct GLXContext glXCreateContextWithConfigSGIX Display *dpy GLXFBConfigSGIX config int render_type GLXContext share_list Bool direct GLXPbufferSGIX glXCreateGLXPbufferSGIX Display *dpy GLXFBConfigSGIX config unsigned int width unsigned int height int *attrib_list GLXPixmap glXCreateGLXPixmap Display *dpy XVisualInfo *visual Pixmap pixmap GLXPixmap glXCreateGLXPixmapMESA Display *dpy XVisualInfo *visual Pixmap pixmap Colormap cmap GLXPixmap glXCreateGLXPixmapWithConfigSGIX Display *dpy GLXFBConfigSGIX config Pixmap pixmap GLXVideoSourceSGIX glXCreateGLXVideoSourceSGIX Display *display int screen VLServer server VLPath path int nodeClass VLNode drainNode GLXContext glXCreateNewContext Display *dpy GLXFBConfig config int render_type GLXContext share_list Bool direct GLXPbuffer glXCreatePbuffer Display *dpy GLXFBConfig config const int *attrib_list GLXPixmap glXCreatePixmap Display *dpy GLXFBConfig config Pixmap pixmap const int *attrib_list GLXWindow glXCreateWindow Display *dpy GLXFBConfig config Window win const int *attrib_list void glXCushionSGI Display *dpy Window window float cushion Bool glXDelayBeforeSwapNV Display *dpy GLXDrawable drawable GLfloat seconds Bool glXDeleteAssociatedContextAMD GLXContext ctx void glXDestroyContext Display *dpy GLXContext ctx void glXDestroyGLXPbufferSGIX Display *dpy GLXPbufferSGIX pbuf void glXDestroyGLXPixmap Display *dpy GLXPixmap pixmap void glXDestroyGLXVideoSourceSGIX Display *dpy GLXVideoSourceSGIX glxvideosource int glXDestroyHyperpipeConfigSGIX Display *dpy int hpId void glXDestroyPbuffer Display *dpy GLXPbuffer pbuf void glXDestroyPixmap Display *dpy GLXPixmap pixmap void glXDestroyWindow Display *dpy GLXWindow win GLXVideoCaptureDeviceNV *glXEnumerateVideoCaptureDevicesNV Display *dpy int screen int *nelements unsigned int *glXEnumerateVideoDevicesNV Display *dpy int screen int *nelements void glXFreeContextEXT Display *dpy GLXContext context unsigned int glXGetAGPOffsetMESA const void *pointer const char *glXGetClientString Display *dpy int name int glXGetConfig Display *dpy XVisualInfo *visual int attrib int *value unsigned int glXGetContextGPUIDAMD GLXContext ctx GLXContextID glXGetContextIDEXT const GLXContext context GLXContext glXGetCurrentAssociatedContextAMD GLXContext glXGetCurrentContext Display *glXGetCurrentDisplayEXT Display *glXGetCurrentDisplay GLXDrawable glXGetCurrentDrawable GLXDrawable glXGetCurrentReadDrawableSGI GLXDrawable glXGetCurrentReadDrawable int glXGetFBConfigAttrib Display *dpy GLXFBConfig config int attribute int *value int glXGetFBConfigAttribSGIX Display *dpy GLXFBConfigSGIX config int attribute int *value GLXFBConfigSGIX glXGetFBConfigFromVisualSGIX Display *dpy XVisualInfo *vis GLXFBConfig *glXGetFBConfigs Display *dpy int screen int *nelements unsigned int glXGetGPUIDsAMD unsigned int maxCount unsigned int *ids int glXGetGPUInfoAMD unsigned int id int property GLenum dataType unsigned int size void *data Bool glXGetMscRateOML Display *dpy GLXDrawable drawable int32_t *numerator int32_t *denominator __GLXextFuncPtr glXGetProcAddressARB const GLubyte *procName __GLXextFuncPtr glXGetProcAddress const GLubyte *procName void glXGetSelectedEvent Display *dpy GLXDrawable draw unsigned long *event_mask void glXGetSelectedEventSGIX Display *dpy GLXDrawable drawable unsigned long *mask Bool glXGetSyncValuesOML Display *dpy GLXDrawable drawable int64_t *ust int64_t *msc int64_t *sbc Status glXGetTransparentIndexSUN Display *dpy Window overlay Window underlay long *pTransparentIndex int glXGetVideoDeviceNV Display *dpy int screen int numVideoDevices GLXVideoDeviceNV *pVideoDevice int glXGetVideoInfoNV Display *dpy int screen GLXVideoDeviceNV VideoDevice unsigned long *pulCounterOutputPbuffer unsigned long *pulCounterOutputVideo int glXGetVideoSyncSGI unsigned int *count XVisualInfo *glXGetVisualFromFBConfig Display *dpy GLXFBConfig config XVisualInfo *glXGetVisualFromFBConfigSGIX Display *dpy GLXFBConfigSGIX config int glXHyperpipeAttribSGIX Display *dpy int timeSlice int attrib int size void *attribList int glXHyperpipeConfigSGIX Display *dpy int networkId int npipes GLXHyperpipeConfigSGIX *cfg int *hpId GLXContext glXImportContextEXT Display *dpy GLXContextID contextID Bool glXIsDirect Display *dpy GLXContext ctx Bool glXJoinSwapGroupNV Display *dpy GLXDrawable drawable GLuint group void glXJoinSwapGroupSGIX Display *dpy GLXDrawable drawable GLXDrawable member void glXLockVideoCaptureDeviceNV Display *dpy GLXVideoCaptureDeviceNV device Bool glXMakeAssociatedContextCurrentAMD GLXContext ctx Bool glXMakeContextCurrent Display *dpy GLXDrawable draw GLXDrawable read GLXContext ctx Bool glXMakeCurrent Display *dpy GLXDrawable drawable GLXContext ctx Bool glXMakeCurrentReadSGI Display *dpy GLXDrawable draw GLXDrawable read GLXContext ctx int glXQueryChannelDeltasSGIX Display *display int screen int channel int *x int *y int *w int *h int glXQueryChannelRectSGIX Display *display int screen int channel int *dx int *dy int *dw int *dh int glXQueryContext Display *dpy GLXContext ctx int attribute int *value int glXQueryContextInfoEXT Display *dpy GLXContext context int attribute int *value Bool glXQueryCurrentRendererIntegerMESA int attribute unsigned int *value const char *glXQueryCurrentRendererStringMESA int attribute void glXQueryDrawable Display *dpy GLXDrawable draw int attribute unsigned int *value Bool glXQueryExtension Display *dpy int *errorb int *event const char *glXQueryExtensionsString Display *dpy int screen Bool glXQueryFrameCountNV Display *dpy int screen GLuint *count int glXQueryGLXPbufferSGIX Display *dpy GLXPbufferSGIX pbuf int attribute unsigned int *value int glXQueryHyperpipeAttribSGIX Display *dpy int timeSlice int attrib int size void *returnAttribList int glXQueryHyperpipeBestAttribSGIX Display *dpy int timeSlice int attrib int size void *attribList void *returnAttribList GLXHyperpipeConfigSGIX *glXQueryHyperpipeConfigSGIX Display *dpy int hpId int *npipes GLXHyperpipeNetworkSGIX *glXQueryHyperpipeNetworkSGIX Display *dpy int *npipes Bool glXQueryMaxSwapBarriersSGIX Display *dpy int screen int *max Bool glXQueryMaxSwapGroupsNV Display *dpy int screen GLuint *maxGroups GLuint *maxBarriers Bool glXQueryRendererIntegerMESA Display *dpy int screen int renderer int attribute unsigned int *value const char *glXQueryRendererStringMESA Display *dpy int screen int renderer int attribute const char *glXQueryServerString Display *dpy int screen int name Bool glXQuerySwapGroupNV Display *dpy GLXDrawable drawable GLuint *group GLuint *barrier Bool glXQueryVersion Display *dpy int *maj int *min int glXQueryVideoCaptureDeviceNV Display *dpy GLXVideoCaptureDeviceNV device int attribute int *value Bool glXReleaseBuffersMESA Display *dpy GLXDrawable drawable void glXReleaseTexImageEXT Display *dpy GLXDrawable drawable int buffer void glXReleaseVideoCaptureDeviceNV Display *dpy GLXVideoCaptureDeviceNV device int glXReleaseVideoDeviceNV Display *dpy int screen GLXVideoDeviceNV VideoDevice int glXReleaseVideoImageNV Display *dpy GLXPbuffer pbuf Bool glXResetFrameCountNV Display *dpy int screen void glXSelectEvent Display *dpy GLXDrawable draw unsigned long event_mask void glXSelectEventSGIX Display *dpy GLXDrawable drawable unsigned long mask int glXSendPbufferToVideoNV Display *dpy GLXPbuffer pbuf int iBufferType unsigned long *pulCounterPbuffer GLboolean bBlock Bool glXSet3DfxModeMESA int mode void glXSwapBuffers Display *dpy GLXDrawable drawable int64_t glXSwapBuffersMscOML Display *dpy GLXDrawable drawable int64_t target_msc int64_t divisor int64_t remainder void glXSwapIntervalEXT Display *dpy GLXDrawable drawable int interval int glXSwapIntervalSGI int interval void glXUseXFont Font font int first int count int list Bool glXWaitForMscOML Display *dpy GLXDrawable drawable int64_t target_msc int64_t divisor int64_t remainder int64_t *ust int64_t *msc int64_t *sbc Bool glXWaitForSbcOML Display *dpy GLXDrawable drawable int64_t target_sbc int64_t *ust int64_t *msc int64_t *sbc void glXWaitGL int glXWaitVideoSyncSGI int divisor int remainder unsigned int *count void glXWaitX ================================================ FILE: server/registry/reg.py ================================================ #!/usr/bin/python3 -i # # Copyright (c) 2013-2014 The Khronos Group Inc. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and/or associated documentation files (the # "Materials"), to deal in the Materials without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Materials, and to # permit persons to whom the Materials are furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Materials. # # THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. import io,os,re,string,sys from lxml import etree def write( *args, **kwargs ): file = kwargs.pop('file',sys.stdout) end = kwargs.pop( 'end','\n') file.write( ' '.join([str(arg) for arg in args]) ) file.write( end ) # noneStr - returns string argument, or "" if argument is None. # Used in converting lxml Elements into text. # str - string to convert def noneStr(str): if (str): return str else: return "" # matchAPIProfile - returns whether an API and profile # being generated matches an element's profile # api - string naming the API to match # profile - string naming the profile to match # elem - Element which (may) have 'api' and 'profile' # attributes to match to. # If a tag is not present in the Element, the corresponding API # or profile always matches. # Otherwise, the tag must exactly match the API or profile. # Thus, if 'profile' = core: # with no attribute will match # will match # will not match # Possible match conditions: # Requested Element # Profile Profile # --------- -------- # None None Always matches # 'string' None Always matches # None 'string' Does not match. Can't generate multiple APIs # or profiles, so if an API/profile constraint # is present, it must be asked for explicitly. # 'string' 'string' Strings must match # # ** In the future, we will allow regexes for the attributes, # not just strings, so that api="^(gl|gles2)" will match. Even # this isn't really quite enough, we might prefer something # like "gl(core)|gles1(common-lite)". def matchAPIProfile(api, profile, elem): """Match a requested API & profile name to a api & profile attributes of an Element""" match = True # Match 'api', if present if ('api' in elem.attrib): if (api == None): raise UserWarning("No API requested, but 'api' attribute is present with value '" + elem.get('api') + "'") elif (api != elem.get('api')): # Requested API doesn't match attribute return False if ('profile' in elem.attrib): if (profile == None): raise UserWarning("No profile requested, but 'profile' attribute is present with value '" + elem.get('profile') + "'") elif (profile != elem.get('profile')): # Requested profile doesn't match attribute return False return True # BaseInfo - base class for information about a registry feature # (type/group/enum/command/API/extension). # required - should this feature be defined during header generation # (has it been removed by a profile or version)? # declared - has this feature been defined already? # elem - lxml.etree Element for this feature # resetState() - reset required/declared to initial values. Used # prior to generating a new API interface. class BaseInfo: """Represents the state of a registry feature, used during API generation""" def __init__(self, elem): self.required = False self.declared = False self.elem = elem def resetState(self): self.required = False self.declared = False # TypeInfo - registry information about a type. No additional state # beyond BaseInfo is required. class TypeInfo(BaseInfo): """Represents the state of a registry type""" def __init__(self, elem): BaseInfo.__init__(self, elem) # GroupInfo - registry information about a group of related enums. # enums - dictionary of enum names which are in the group class GroupInfo(BaseInfo): """Represents the state of a registry enumerant group""" def __init__(self, elem): BaseInfo.__init__(self, elem) self.enums = {} # EnumInfo - registry information about an enum # type - numeric type of the value of the tag # ( '' for GLint, 'u' for GLuint, 'ull' for GLuint64 ) class EnumInfo(BaseInfo): """Represents the state of a registry enum""" def __init__(self, elem): BaseInfo.__init__(self, elem) self.type = elem.get('type') if (self.type == None): self.type = '' # CmdInfo - registry information about a command # glxtype - type of GLX protocol { None, 'render', 'single', 'vendor' } # glxopcode - GLX protocol opcode { None, number } # glxequiv - equivalent command at GLX dispatch level { None, string } # vecequiv - equivalent vector form of a command taking multiple scalar args # { None, string } class CmdInfo(BaseInfo): """Represents the state of a registry command""" def __init__(self, elem): BaseInfo.__init__(self, elem) self.glxtype = None self.glxopcode = None self.glxequiv = None self.vecequiv = None # FeatureInfo - registry information about an API # or # name - feature name string (e.g. 'GL_ARB_multitexture') # number - feature version number (e.g. 1.2). # features are unversioned and assigned version number 0. # category - category, e.g. VERSION or ARB/KHR/OES/ETC/vendor # emit - has this feature been defined already? class FeatureInfo(BaseInfo): """Represents the state of an API feature (version/extension)""" def __init__(self, elem): BaseInfo.__init__(self, elem) self.name = elem.get('name') # Determine element category (vendor). Only works # for elements. if (elem.tag == 'feature'): self.category = 'VERSION' self.number = elem.get('number') else: self.category = self.name.split('_', 2)[1] self.number = "0" self.emit = False # Primary sort key for regSortFeatures. # Sorts by category of the feature name string: # Core API features (those defined with a tag) # ARB/KHR/OES (Khronos extensions) # other (EXT/vendor extensions) def regSortCategoryKey(feature): if (feature.elem.tag == 'feature'): return 0 elif (feature.category == 'ARB' or feature.category == 'KHR' or feature.category == 'OES'): return 1 else: return 2 # Secondary sort key for regSortFeatures. # Sorts by extension name. def regSortNameKey(feature): return feature.name # Tertiary sort key for regSortFeatures. # Sorts by feature version number. # elements all have version number "0" def regSortNumberKey(feature): return feature.number # regSortFeatures - default sort procedure for features. # Sorts by primary key of feature category, # then by feature name within the category, # then by version number def regSortFeatures(featureList): featureList.sort(key = regSortNumberKey) featureList.sort(key = regSortNameKey) featureList.sort(key = regSortCategoryKey) # GeneratorOptions - base class for options used during header production # These options are target language independent, and used by # Registry.apiGen() and by base OutputGenerator objects. # # Members # filename - name of file to generate, or None to write to stdout. # apiname - string matching 'apiname' attribute, e.g. 'gl'. # profile - string specifying API profile , e.g. 'core', or None. # versions - regex matching API versions to process interfaces for. # Normally '.*' or '[0-9]\.[0-9]' to match all defined versions. # emitversions - regex matching API versions to actually emit # interfaces for (though all requested versions are considered # when deciding which interfaces to generate). For GL 4.3 glext.h, # this might be '1\.[2-5]|[2-4]\.[0-9]'. # defaultExtensions - If not None, a string which must in its # entirety match the pattern in the "supported" attribute of # the . Defaults to None. Usually the same as apiname. # addExtensions - regex matching names of additional extensions # to include. Defaults to None. # removeExtensions - regex matching names of extensions to # remove (after defaultExtensions and addExtensions). Defaults # to None. # sortProcedure - takes a list of FeatureInfo objects and sorts # them in place to a preferred order in the generated output. # Default is core API versions, ARB/KHR/OES extensions, all # other extensions, alphabetically within each group. # The regex patterns can be None or empty, in which case they match # nothing. class GeneratorOptions: """Represents options during header production from an API registry""" def __init__(self, filename = None, apiname = None, profile = None, versions = '.*', emitversions = '.*', defaultExtensions = None, addExtensions = None, removeExtensions = None, sortProcedure = regSortFeatures): self.filename = filename self.apiname = apiname self.profile = profile self.versions = self.emptyRegex(versions) self.emitversions = self.emptyRegex(emitversions) self.defaultExtensions = defaultExtensions self.addExtensions = self.emptyRegex(addExtensions) self.removeExtensions = self.emptyRegex(removeExtensions) self.sortProcedure = sortProcedure # # Substitute a regular expression which matches no version # or extension names for None or the empty string. def emptyRegex(self,pat): if (pat == None or pat == ''): return '_nomatch_^' else: return pat # CGeneratorOptions - subclass of GeneratorOptions. # # Adds options used by COutputGenerator objects during C language header # generation. # # Additional members # prefixText - list of strings to prefix generated header with # (usually a copyright statement + calling convention macros). # protectFile - True if multiple inclusion protection should be # generated (based on the filename) around the entire header. # protectFeature - True if #ifndef..#endif protection should be # generated around a feature interface in the header file. # genFuncPointers - True if function pointer typedefs should be # generated # protectProto - True if #ifdef..#endif protection should be # generated around prototype declarations # protectProtoStr - #ifdef symbol to use around prototype # declarations, if protected # apicall - string to use for the function declaration prefix, # such as APICALL on Windows. # apientry - string to use for the calling convention macro, # in typedefs, such as APIENTRY. # apientryp - string to use for the calling convention macro # in function pointer typedefs, such as APIENTRYP. class CGeneratorOptions(GeneratorOptions): """Represents options during C header production from an API registry""" def __init__(self, filename = None, apiname = None, profile = None, versions = '.*', emitversions = '.*', defaultExtensions = None, addExtensions = None, removeExtensions = None, sortProcedure = regSortFeatures, prefixText = "", genFuncPointers = True, protectFile = True, protectFeature = True, protectProto = True, protectProtoStr = True, apicall = '', apientry = '', apientryp = ''): GeneratorOptions.__init__(self, filename, apiname, profile, versions, emitversions, defaultExtensions, addExtensions, removeExtensions, sortProcedure) self.prefixText = prefixText self.genFuncPointers = genFuncPointers self.protectFile = protectFile self.protectFeature = protectFeature self.protectProto = protectProto self.protectProtoStr = protectProtoStr self.apicall = apicall self.apientry = apientry self.apientryp = apientryp # OutputGenerator - base class for generating API interfaces. # Manages basic logic, logging, and output file control # Derived classes actually generate formatted output. # # ---- methods ---- # OutputGenerator(errFile, warnFile, diagFile) # errFile, warnFile, diagFile - file handles to write errors, # warnings, diagnostics to. May be None to not write. # logMsg(level, *args) - log messages of different categories # level - 'error', 'warn', or 'diag'. 'error' will also # raise a UserWarning exception # *args - print()-style arguments # beginFile(genOpts) - start a new interface file # genOpts - GeneratorOptions controlling what's generated and how # endFile() - finish an interface file, closing it when done # beginFeature(interface, emit) - write interface for a feature # and tag generated features as having been done. # interface - element for the / to generate # emit - actually write to the header only when True # endFeature() - finish an interface. # genType(typeinfo,name) - generate interface for a type # typeinfo - TypeInfo for a type # genEnum(enuminfo, name) - generate interface for an enum # enuminfo - EnumInfo for an enum # name - enum name # genCmd(cmdinfo) - generate interface for a command # cmdinfo - CmdInfo for a command class OutputGenerator: """Generate specified API interfaces in a specific style, such as a C header""" def __init__(self, errFile = sys.stderr, warnFile = sys.stderr, diagFile = sys.stdout): self.outFile = None self.errFile = errFile self.warnFile = warnFile self.diagFile = diagFile # Internal state self.featureName = None self.genOpts = None # # logMsg - write a message of different categories to different # destinations. # level - # 'diag' (diagnostic, voluminous) # 'warn' (warning) # 'error' (fatal error - raises exception after logging) # *args - print()-style arguments to direct to corresponding log def logMsg(self, level, *args): """Log a message at the given level. Can be ignored or log to a file""" if (level == 'error'): strfile = io.StringIO() write('ERROR:', *args, file=strfile) if (self.errFile != None): write(strfile.getvalue(), file=self.errFile) raise UserWarning(strfile.getvalue()) elif (level == 'warn'): if (self.warnFile != None): write('WARNING:', *args, file=self.warnFile) elif (level == 'diag'): if (self.diagFile != None): write('DIAG:', *args, file=self.diagFile) else: raise UserWarning( '*** FATAL ERROR in Generator.logMsg: unknown level:' + level) # def beginFile(self, genOpts): self.genOpts = genOpts # # Open specified output file. Not done in constructor since a # Generator can be used without writing to a file. if (self.genOpts.filename != None): self.outFile = open(self.genOpts.filename, 'w') else: self.outFile = sys.stdout def endFile(self): self.errFile and self.errFile.flush() self.warnFile and self.warnFile.flush() self.diagFile and self.diagFile.flush() self.outFile.flush() if (self.outFile != sys.stdout and self.outFile != sys.stderr): self.outFile.close() self.genOpts = None # def beginFeature(self, interface, emit): self.emit = emit self.featureName = interface.get('name') # If there's an additional 'protect' attribute in the feature, save it self.featureExtraProtect = interface.get('protect') def endFeature(self): # Derived classes responsible for emitting feature self.featureName = None self.featureExtraProtect = None # # Type generation def genType(self, typeinfo, name): if (self.featureName == None): raise UserWarning('Attempt to generate type', name, 'when not in feature') # # Enumerant generation def genEnum(self, enuminfo, name): if (self.featureName == None): raise UserWarning('Attempt to generate enum', name, 'when not in feature') # # Command generation def genCmd(self, cmd, name): if (self.featureName == None): raise UserWarning('Attempt to generate command', name, 'when not in feature') # COutputGenerator - subclass of OutputGenerator. # Generates C-language API interfaces. # # ---- methods ---- # COutputGenerator(errFile, warnFile, diagFile) - args as for # OutputGenerator. Defines additional internal state. # makeCDecls(cmd) - return C prototype and function pointer typedef for a # Element, as a list of two strings # cmd - Element for the # newline() - print a newline to the output file (utility function) # ---- methods overriding base class ---- # beginFile(genOpts) # endFile() # beginFeature(interface, emit) # endFeature() # genType(typeinfo,name) - generate interface for a type # genEnum(enuminfo, name) # genCmd(cmdinfo) class COutputGenerator(OutputGenerator): """Generate specified API interfaces in a specific style, such as a C header""" def __init__(self, errFile = sys.stderr, warnFile = sys.stderr, diagFile = sys.stdout): OutputGenerator.__init__(self, errFile, warnFile, diagFile) # Internal state - accumulators for different inner block text self.typeBody = '' self.enumBody = '' self.cmdBody = '' # # makeCDecls - return C prototype and function pointer typedef for a # command, as a two-element list of strings. # cmd - Element containing a tag def makeCDecls(self, cmd): """Generate C function pointer typedef for Element""" proto = cmd.find('proto') params = cmd.findall('param') # Begin accumulating prototype and typedef strings pdecl = self.genOpts.apicall tdecl = 'typedef ' # # Insert the function return type/name. # For prototypes, add APIENTRY macro before the name # For typedefs, add (APIENTRYP ) around the name and # use the PFNGLCMDNAMEPROC nameng convention. # Done by walking the tree for element by element. # lxml.etree has elem.text followed by (elem[i], elem[i].tail) # for each child element and any following text # Leading text pdecl += noneStr(proto.text) tdecl += noneStr(proto.text) # For each child element, if it's a wrap in appropriate # declaration. Otherwise append its contents and tail contents. for elem in proto: text = noneStr(elem.text) tail = noneStr(elem.tail) if (elem.tag == 'name'): pdecl += self.genOpts.apientry + text + tail tdecl += '(' + self.genOpts.apientryp + 'PFN' + text.upper() + 'PROC' + tail + ')' else: pdecl += text + tail tdecl += text + tail # Now add the parameter declaration list, which is identical # for prototypes and typedefs. Concatenate all the text from # a node without the tags. No tree walking required # since all tags are ignored. n = len(params) paramdecl = ' (' if n > 0: for i in range(0,n): paramdecl += ''.join([t for t in params[i].itertext()]) if (i < n - 1): paramdecl += ', ' else: paramdecl += 'void' paramdecl += ");\n"; return [ pdecl + paramdecl, tdecl + paramdecl ] # def newline(self): write('', file=self.outFile) # def beginFile(self, genOpts): OutputGenerator.beginFile(self, genOpts) # C-specific # # Multiple inclusion protection & C++ wrappers. if (genOpts.protectFile and self.genOpts.filename): headerSym = '__' + re.sub('\.h', '_h_', os.path.basename(self.genOpts.filename)) write('#ifndef', headerSym, file=self.outFile) write('#define', headerSym, '1', file=self.outFile) self.newline() write('#ifdef __cplusplus', file=self.outFile) write('extern "C" {', file=self.outFile) write('#endif', file=self.outFile) self.newline() # # User-supplied prefix text, if any (list of strings) if (genOpts.prefixText): for s in genOpts.prefixText: write(s, file=self.outFile) # # Some boilerplate describing what was generated - this # will probably be removed later since the extensions # pattern may be very long. write('/* Generated C header for:', file=self.outFile) write(' * API:', genOpts.apiname, file=self.outFile) if (genOpts.profile): write(' * Profile:', genOpts.profile, file=self.outFile) write(' * Versions considered:', genOpts.versions, file=self.outFile) write(' * Versions emitted:', genOpts.emitversions, file=self.outFile) write(' * Default extensions included:', genOpts.defaultExtensions, file=self.outFile) write(' * Additional extensions included:', genOpts.addExtensions, file=self.outFile) write(' * Extensions removed:', genOpts.removeExtensions, file=self.outFile) write(' */', file=self.outFile) def endFile(self): # C-specific # Finish C++ wrapper and multiple inclusion protection self.newline() write('#ifdef __cplusplus', file=self.outFile) write('}', file=self.outFile) write('#endif', file=self.outFile) if (self.genOpts.protectFile and self.genOpts.filename): self.newline() write('#endif', file=self.outFile) # Finish processing in superclass OutputGenerator.endFile(self) def beginFeature(self, interface, emit): # Start processing in superclass OutputGenerator.beginFeature(self, interface, emit) # C-specific # Accumulate types, enums, function pointer typedefs, end function # prototypes separately for this feature. They're only printed in # endFeature(). self.typeBody = '' self.enumBody = '' self.cmdPointerBody = '' self.cmdBody = '' def endFeature(self): # C-specific # Actually write the interface to the output file. if (self.emit): self.newline() if (self.genOpts.protectFeature): write('#ifndef', self.featureName, file=self.outFile) write('#define', self.featureName, '1', file=self.outFile) if (self.typeBody != ''): write(self.typeBody, end='', file=self.outFile) # # Don't add additional protection for derived type declarations, # which may be needed by other features later on. if (self.featureExtraProtect != None): write('#ifdef', self.featureExtraProtect, file=self.outFile) if (self.enumBody != ''): write(self.enumBody, end='', file=self.outFile) if (self.genOpts.genFuncPointers and self.cmdPointerBody != ''): write(self.cmdPointerBody, end='', file=self.outFile) if (self.cmdBody != ''): if (self.genOpts.protectProto): write('#ifdef', self.genOpts.protectProtoStr, file=self.outFile) write(self.cmdBody, end='', file=self.outFile) if (self.genOpts.protectProto): write('#endif', file=self.outFile) if (self.featureExtraProtect != None): write('#endif /*', self.featureExtraProtect, '*/', file=self.outFile) if (self.genOpts.protectFeature): write('#endif /*', self.featureName, '*/', file=self.outFile) # Finish processing in superclass OutputGenerator.endFeature(self) # # Type generation def genType(self, typeinfo, name): OutputGenerator.genType(self, typeinfo, name) # # Replace tags with an APIENTRY-style string # (from self.genOpts). Copy other text through unchanged. # If the resulting text is an empty string, don't emit it. typeElem = typeinfo.elem s = noneStr(typeElem.text) for elem in typeElem: if (elem.tag == 'apientry'): s += self.genOpts.apientry + noneStr(elem.tail) else: s += noneStr(elem.text) + noneStr(elem.tail) if (len(s) > 0): self.typeBody += s + "\n" # # Enumerant generation def genEnum(self, enuminfo, name): OutputGenerator.genEnum(self, enuminfo, name) # # EnumInfo.type is a C value suffix (e.g. u, ull) self.enumBody += '#define ' + name.ljust(33) + ' ' + enuminfo.elem.get('value') # # Handle non-integer 'type' fields by using it as the C value suffix t = enuminfo.elem.get('type') if (t != '' and t != 'i'): self.enumBody += enuminfo.type self.enumBody += "\n" # # Command generation def genCmd(self, cmdinfo, name): OutputGenerator.genCmd(self, cmdinfo, name) # decls = self.makeCDecls(cmdinfo.elem) self.cmdBody += decls[0] if (self.genOpts.genFuncPointers): self.cmdPointerBody += decls[1] # Registry - object representing an API registry, loaded from an XML file # Members # tree - ElementTree containing the root # typedict - dictionary of TypeInfo objects keyed by type name # groupdict - dictionary of GroupInfo objects keyed by group name # enumdict - dictionary of EnumInfo objects keyed by enum name # cmddict - dictionary of CmdInfo objects keyed by command name # apidict - dictionary of Elements keyed by API name # extensions - list of Elements # extdict - dictionary of Elements keyed by extension name # gen - OutputGenerator object used to write headers / messages # genOpts - GeneratorOptions object used to control which # fetures to write and how to format them # emitFeatures - True to actually emit features for a version / extension, # or False to just treat them as emitted # Public methods # loadElementTree(etree) - load registry from specified ElementTree # loadFile(filename) - load registry from XML file # setGenerator(gen) - OutputGenerator to use # parseTree() - parse the registry once loaded & create dictionaries # dumpReg(maxlen, filehandle) - diagnostic to dump the dictionaries # to specified file handle (default stdout). Truncates type / # enum / command elements to maxlen characters (default 80) # generator(g) - specify the output generator object # apiGen(apiname, genOpts) - generate API headers for the API type # and profile specified in genOpts, but only for the versions and # extensions specified there. # apiReset() - call between calls to apiGen() to reset internal state # validateGroups() - call to verify that each or # with a 'group' attribute matches an actual existing group. # Private methods # addElementInfo(elem,info,infoName,dictionary) - add feature info to dict # lookupElementInfo(fname,dictionary) - lookup feature info in dict class Registry: """Represents an API registry loaded from XML""" def __init__(self): self.tree = None self.typedict = {} self.groupdict = {} self.enumdict = {} self.cmddict = {} self.apidict = {} self.extensions = [] self.extdict = {} # A default output generator, so commands prior to apiGen can report # errors via the generator object. self.gen = OutputGenerator() self.genOpts = None self.emitFeatures = False def loadElementTree(self, tree): """Load ElementTree into a Registry object and parse it""" self.tree = tree self.parseTree() def loadFile(self, file): """Load an API registry XML file into a Registry object and parse it""" self.tree = etree.parse(file) self.parseTree() def setGenerator(self, gen): """Specify output generator object. None restores the default generator""" self.gen = gen # addElementInfo - add information about an element to the # corresponding dictionary # elem - ///// Element # info - corresponding {Type|Group|Enum|Cmd|Feature}Info object # infoName - 'type' / 'group' / 'enum' / 'command' / 'feature' / 'extension' # dictionary - self.{type|group|enum|cmd|api|ext}dict # If the Element has an 'api' attribute, the dictionary key is the # tuple (name,api). If not, the key is the name. 'name' is an # attribute of the Element def addElementInfo(self, elem, info, infoName, dictionary): if ('api' in elem.attrib): key = (elem.get('name'),elem.get('api')) else: key = elem.get('name') if key in dictionary: self.gen.logMsg('warn', '*** Attempt to redefine', infoName, 'with key:', key) else: dictionary[key] = info # # lookupElementInfo - find a {Type|Enum|Cmd}Info object by name. # If an object qualified by API name exists, use that. # fname - name of type / enum / command # dictionary - self.{type|enum|cmd}dict def lookupElementInfo(self, fname, dictionary): key = (fname, self.genOpts.apiname) if (key in dictionary): # self.gen.logMsg('diag', 'Found API-specific element for feature', fname) return dictionary[key] elif (fname in dictionary): # self.gen.logMsg('diag', 'Found generic element for feature', fname) return dictionary[fname] else: return None def parseTree(self): """Parse the registry Element, once created""" # This must be the Element for the root self.reg = self.tree.getroot() # # Create dictionary of registry types from toplevel tags # and add 'name' attribute to each tag (where missing) # based on its element. # # There's usually one block; more are OK # Required attributes: 'name' or nested tag contents self.typedict = {} for type in self.reg.findall('types/type'): # If the doesn't already have a 'name' attribute, set # it from contents of its tag. if (type.get('name') == None): type.attrib['name'] = type.find('name').text self.addElementInfo(type, TypeInfo(type), 'type', self.typedict) # # Create dictionary of registry groups from toplevel tags. # # There's usually one block; more are OK. # Required attributes: 'name' self.groupdict = {} for group in self.reg.findall('groups/group'): self.addElementInfo(group, GroupInfo(group), 'group', self.groupdict) # # Create dictionary of registry enums from toplevel tags # # There are usually many tags in different namespaces, but # these are functional namespaces of the values, while the actual # enum names all share the dictionary. # Required attributes: 'name', 'value' self.enumdict = {} for enum in self.reg.findall('enums/enum'): self.addElementInfo(enum, EnumInfo(enum), 'enum', self.enumdict) # # Create dictionary of registry commands from tags # and add 'name' attribute to each tag (where missing) # based on its element. # # There's usually only one block; more are OK. # Required attributes: 'name' or tag contents self.cmddict = {} for cmd in self.reg.findall('commands/command'): # If the doesn't already have a 'name' attribute, set # it from contents of its tag. if (cmd.get('name') == None): cmd.attrib['name'] = cmd.find('proto/name').text ci = CmdInfo(cmd) self.addElementInfo(cmd, ci, 'command', self.cmddict) # # Create dictionaries of API and extension interfaces # from toplevel and tags. # self.apidict = {} for feature in self.reg.findall('feature'): ai = FeatureInfo(feature) self.addElementInfo(feature, ai, 'feature', self.apidict) self.extensions = self.reg.findall('extensions/extension') self.extdict = {} for feature in self.extensions: ei = FeatureInfo(feature) self.addElementInfo(feature, ei, 'extension', self.extdict) def dumpReg(self, maxlen = 40, filehandle = sys.stdout): """Dump all the dictionaries constructed from the Registry object""" write('***************************************', file=filehandle) write(' ** Dumping Registry contents **', file=filehandle) write('***************************************', file=filehandle) write('// Types', file=filehandle) for name in self.typedict: tobj = self.typedict[name] write(' Type', name, '->', etree.tostring(tobj.elem)[0:maxlen], file=filehandle) write('// Groups', file=filehandle) for name in self.groupdict: gobj = self.groupdict[name] write(' Group', name, '->', etree.tostring(gobj.elem)[0:maxlen], file=filehandle) write('// Enums', file=filehandle) for name in self.enumdict: eobj = self.enumdict[name] write(' Enum', name, '->', etree.tostring(eobj.elem)[0:maxlen], file=filehandle) write('// Commands', file=filehandle) for name in self.cmddict: cobj = self.cmddict[name] write(' Command', name, '->', etree.tostring(cobj.elem)[0:maxlen], file=filehandle) write('// APIs', file=filehandle) for key in self.apidict: write(' API Version ', key, '->', etree.tostring(self.apidict[key].elem)[0:maxlen], file=filehandle) write('// Extensions', file=filehandle) for key in self.extdict: write(' Extension', key, '->', etree.tostring(self.extdict[key].elem)[0:maxlen], file=filehandle) # write('***************************************', file=filehandle) # write(' ** Dumping XML ElementTree **', file=filehandle) # write('***************************************', file=filehandle) # write(etree.tostring(self.tree.getroot(),pretty_print=True), file=filehandle) # # typename - name of type # required - boolean (to tag features as required or not) def markTypeRequired(self, typename, required): """Require (along with its dependencies) or remove (but not its dependencies) a type""" self.gen.logMsg('diag', '*** tagging type:', typename, '-> required =', required) # Get TypeInfo object for tag corresponding to typename type = self.lookupElementInfo(typename, self.typedict) if (type != None): # Tag required type dependencies as required. # This DOES NOT un-tag dependencies in a tag. # See comments in markRequired() below for the reason. if (required and ('requires' in type.elem.attrib)): depType = type.elem.get('requires') self.gen.logMsg('diag', '*** Generating dependent type', depType, 'for type', typename) self.markTypeRequired(depType, required) type.required = required else: self.gen.logMsg('warn', '*** type:', typename , 'IS NOT DEFINED') # # features - Element for or tag # required - boolean (to tag features as required or not) def markRequired(self, features, required): """Require or remove features specified in the Element""" self.gen.logMsg('diag', '*** markRequired (features = , required =', required, ')') # Loop over types, enums, and commands in the tag # @@ It would be possible to respect 'api' and 'profile' attributes # in individual features, but that's not done yet. for typeElem in features.findall('type'): self.markTypeRequired(typeElem.get('name'), required) for enumElem in features.findall('enum'): name = enumElem.get('name') self.gen.logMsg('diag', '*** tagging enum:', name, '-> required =', required) enum = self.lookupElementInfo(name, self.enumdict) if (enum != None): enum.required = required else: self.gen.logMsg('warn', '*** enum:', name , 'IS NOT DEFINED') for cmdElem in features.findall('command'): name = cmdElem.get('name') self.gen.logMsg('diag', '*** tagging command:', name, '-> required =', required) cmd = self.lookupElementInfo(name, self.cmddict) if (cmd != None): cmd.required = required # Tag all parameter types of this command as required. # This DOES NOT remove types of commands in a # tag, because many other commands may use the same type. # We could be more clever and reference count types, # instead of using a boolean. if (required): # Look for in entire tree, # not just immediate children for ptype in cmd.elem.findall('.//ptype'): self.gen.logMsg('diag', '*** markRequired: command implicitly requires dependent type', ptype.text) self.markTypeRequired(ptype.text, required) else: self.gen.logMsg('warn', '*** command:', name, 'IS NOT DEFINED') # # interface - Element for or , containing # and tags # api - string specifying API name being generated # profile - string specifying API profile being generated def requireAndRemoveFeatures(self, interface, api, profile): """Process and tags for a or """ # marks things that are required by this version/profile for feature in interface.findall('require'): if (matchAPIProfile(api, profile, feature)): self.markRequired(feature,True) # marks things that are removed by this version/profile for feature in interface.findall('remove'): if (matchAPIProfile(api, profile, feature)): self.markRequired(feature,False) # # generateFeature - generate a single type / enum / command, # and all its dependencies as needed. # fname - name of feature (// # ftype - type of feature, 'type' | 'enum' | 'command' # dictionary - of *Info objects - self.{type|enum|cmd}dict # genProc - bound function pointer for self.gen.gen{Type|Enum|Cmd} def generateFeature(self, fname, ftype, dictionary, genProc): f = self.lookupElementInfo(fname, dictionary) if (f == None): # No such feature. This is an error, but reported earlier self.gen.logMsg('diag', '*** No entry found for feature', fname, 'returning!') return # # If feature isn't required, or has already been declared, return if (not f.required): self.gen.logMsg('diag', '*** Skipping', ftype, fname, '(not required)') return if (f.declared): self.gen.logMsg('diag', '*** Skipping', ftype, fname, '(already declared)') return # # Pull in dependent type declaration(s) of the feature. # For types, there may be one in the 'required' attribute of the element # For commands, there may be many in tags within the element # For enums, no dependencies are allowed (though perhasps if you # have a uint64 enum, it should require GLuint64) if (ftype == 'type'): if ('requires' in f.elem.attrib): depname = f.elem.get('requires') self.gen.logMsg('diag', '*** Generating required dependent type', depname) self.generateFeature(depname, 'type', self.typedict, self.gen.genType) elif (ftype == 'command'): for ptype in f.elem.findall('.//ptype'): depname = ptype.text self.gen.logMsg('diag', '*** Generating required parameter type', depname) self.generateFeature(depname, 'type', self.typedict, self.gen.genType) # # Actually generate the type only if emitting declarations if self.emitFeatures: self.gen.logMsg('diag', '*** Emitting', ftype, 'decl for', fname) genProc(f, fname) else: self.gen.logMsg('diag', '*** Skipping', ftype, fname, '(not emitting this feature)') # Always mark feature declared, as though actually emitted f.declared = True # # generateRequiredInterface - generate all interfaces required # by an API version or extension # interface - Element for or def generateRequiredInterface(self, interface): """Generate required C interface for specified API version/extension""" # # Loop over all features inside all tags. # tags are ignored (handled in pass 1). for features in interface.findall('require'): for t in features.findall('type'): self.generateFeature(t.get('name'), 'type', self.typedict, self.gen.genType) for e in features.findall('enum'): self.generateFeature(e.get('name'), 'enum', self.enumdict, self.gen.genEnum) for c in features.findall('command'): self.generateFeature(c.get('name'), 'command', self.cmddict, self.gen.genCmd) # # apiGen(genOpts) - generate interface for specified versions # genOpts - GeneratorOptions object with parameters used # by the Generator object. def apiGen(self, genOpts): """Generate interfaces for the specified API type and range of versions""" # self.gen.logMsg('diag', '*******************************************') self.gen.logMsg('diag', ' Registry.apiGen file:', genOpts.filename, 'api:', genOpts.apiname, 'profile:', genOpts.profile) self.gen.logMsg('diag', '*******************************************') # self.genOpts = genOpts # Reset required/declared flags for all features self.apiReset() # # Compile regexps used to select versions & extensions regVersions = re.compile(self.genOpts.versions) regEmitVersions = re.compile(self.genOpts.emitversions) regAddExtensions = re.compile(self.genOpts.addExtensions) regRemoveExtensions = re.compile(self.genOpts.removeExtensions) # # Get all matching API versions & add to list of FeatureInfo features = [] apiMatch = False for key in self.apidict: fi = self.apidict[key] api = fi.elem.get('api') if (api == self.genOpts.apiname): apiMatch = True if (regVersions.match(fi.number)): # Matches API & version #s being generated. Mark for # emission and add to the features[] list . # @@ Could use 'declared' instead of 'emit'? fi.emit = (regEmitVersions.match(fi.number) != None) features.append(fi) if (not fi.emit): self.gen.logMsg('diag', '*** NOT tagging feature api =', api, 'name =', fi.name, 'number =', fi.number, 'for emission (does not match emitversions pattern)') else: self.gen.logMsg('diag', '*** NOT including feature api =', api, 'name =', fi.name, 'number =', fi.number, '(does not match requested versions)') else: self.gen.logMsg('diag', '*** NOT including feature api =', api, 'name =', fi.name, '(does not match requested API)') if (not apiMatch): self.gen.logMsg('warn', '*** No matching API versions found!') # # Get all matching extensions & add to the list. # Start with extensions tagged with 'api' pattern matching the API # being generated. Add extensions matching the pattern specified in # regExtensions, then remove extensions matching the pattern # specified in regRemoveExtensions for key in self.extdict: ei = self.extdict[key] extName = ei.name include = False # # Include extension if defaultExtensions is not None and if the # 'supported' attribute matches defaultExtensions. The regexp in # 'supported' must exactly match defaultExtensions, so bracket # it with ^(pat)$. pat = '^(' + ei.elem.get('supported') + ')$' if (self.genOpts.defaultExtensions and re.match(pat, self.genOpts.defaultExtensions)): self.gen.logMsg('diag', '*** Including extension', extName, "(defaultExtensions matches the 'supported' attribute)") include = True # # Include additional extensions if the extension name matches # the regexp specified in the generator options. This allows # forcing extensions into an interface even if they're not # tagged appropriately in the registry. if (regAddExtensions.match(extName) != None): self.gen.logMsg('diag', '*** Including extension', extName, '(matches explicitly requested extensions to add)') include = True # Remove extensions if the name matches the regexp specified # in generator options. This allows forcing removal of # extensions from an interface even if they're tagged that # way in the registry. if (regRemoveExtensions.match(extName) != None): self.gen.logMsg('diag', '*** Removing extension', extName, '(matches explicitly requested extensions to remove)') include = False # # If the extension is to be included, add it to the # extension features list. if (include): ei.emit = True features.append(ei) else: self.gen.logMsg('diag', '*** NOT including extension', extName, '(does not match api attribute or explicitly requested extensions)') # # Sort the extension features list, if a sort procedure is defined if (self.genOpts.sortProcedure): self.genOpts.sortProcedure(features) # # Pass 1: loop over requested API versions and extensions tagging # types/commands/features as required (in an block) or no # longer required (in an block). It is possible to remove # a feature in one version and restore it later by requiring it in # a later version. # If a profile other than 'None' is being generated, it must # match the profile attribute (if any) of the and # tags. self.gen.logMsg('diag', '*** PASS 1: TAG FEATURES ********************************************') for f in features: self.gen.logMsg('diag', '*** PASS 1: Tagging required and removed features for', f.name) self.requireAndRemoveFeatures(f.elem, self.genOpts.apiname, self.genOpts.profile) # # Pass 2: loop over specified API versions and extensions printing # declarations for required things which haven't already been # generated. self.gen.logMsg('diag', '*** PASS 2: GENERATE INTERFACES FOR FEATURES ************************') self.gen.beginFile(self.genOpts) for f in features: self.gen.logMsg('diag', '*** PASS 2: Generating interface for', f.name) emit = self.emitFeatures = f.emit if (not emit): self.gen.logMsg('diag', '*** PASS 2: NOT declaring feature', f.elem.get('name'), 'because it is not tagged for emission') # Generate the interface (or just tag its elements as having been # emitted, if they haven't been). self.gen.beginFeature(f.elem, emit) self.generateRequiredInterface(f.elem) self.gen.endFeature() self.gen.endFile() # # apiReset - use between apiGen() calls to reset internal state # def apiReset(self): """Reset type/enum/command dictionaries before generating another API""" for type in self.typedict: self.typedict[type].resetState() for enum in self.enumdict: self.enumdict[enum].resetState() for cmd in self.cmddict: self.cmddict[cmd].resetState() for cmd in self.apidict: self.apidict[cmd].resetState() # # validateGroups - check that group= attributes match actual groups # def validateGroups(self): """Validate group= attributes on and tags""" # Keep track of group names not in tags badGroup = {} self.gen.logMsg('diag', '*** VALIDATING GROUP ATTRIBUTES ***') for cmd in self.reg.findall('commands/command'): proto = cmd.find('proto') funcname = cmd.find('proto/name').text if ('group' in proto.attrib.keys()): group = proto.get('group') # self.gen.logMsg('diag', '*** Command ', funcname, ' has return group ', group) if (group not in self.groupdict.keys()): # self.gen.logMsg('diag', '*** Command ', funcname, ' has UNKNOWN return group ', group) if (group not in badGroup.keys()): badGroup[group] = 1 else: badGroup[group] = badGroup[group] + 1 for param in cmd.findall('param'): pname = param.find('name') if (pname != None): pname = pname.text else: pname = type.get('name') if ('group' in param.attrib.keys()): group = param.get('group') if (group not in self.groupdict.keys()): # self.gen.logMsg('diag', '*** Command ', funcname, ' param ', pname, ' has UNKNOWN group ', group) if (group not in badGroup.keys()): badGroup[group] = 1 else: badGroup[group] = badGroup[group] + 1 if (len(badGroup.keys()) > 0): self.gen.logMsg('diag', '*** SUMMARY OF UNRECOGNIZED GROUPS ***') for key in sorted(badGroup.keys()): self.gen.logMsg('diag', ' ', key, ' occurred ', badGroup[key], ' times') ================================================ FILE: server/stdatomic.h ================================================ /* * An implementation of C11 stdatomic.h directly borrowed from FreeBSD * (original copyright follows), with minor modifications for * portability to other systems. Works for recent Clang (that * implement the feature c_atomic) and GCC 4.7+; includes * compatibility for GCC below 4.7 but I wouldn't recommend it. * * Caveats and limitations: * - Only the ``_Atomic parentheses'' notation is implemented, while * the ``_Atomic space'' one is not. * - _Atomic types must be typedef'ed, or programs using them will * not type check correctly (incompatible anonymous structure * types). * - Non-scalar _Atomic types would require runtime support for * runtime locking, which, as far as I know, is not currently * available on any system. */ /*- * Copyright (c) 2011 Ed Schouten * David Chisnall * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/include/stdatomic.h,v 1.10.2.2 2012/05/30 19:21:54 theraven Exp $ */ #ifndef _STDATOMIC_H_ #define _STDATOMIC_H_ #include #include #if !defined(__has_feature) #define __has_feature(x) 0 #endif #if !defined(__has_builtin) #define __has_builtin(x) 0 #endif #if !defined(__GNUC_PREREQ__) #if defined(__GNUC__) && defined(__GNUC_MINOR__) #define __GNUC_PREREQ__(maj, min) \ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) #else #define __GNUC_PREREQ__(maj, min) 0 #endif #endif #if !defined(__CLANG_ATOMICS) && !defined(__GNUC_ATOMICS) #if __has_feature(c_atomic) #define __CLANG_ATOMICS #elif __GNUC_PREREQ__(4, 7) #define __GNUC_ATOMICS #elif !defined(__GNUC__) #error "stdatomic.h does not support your compiler" #endif #endif #if !defined(__CLANG_ATOMICS) #define _Atomic(T) struct { volatile __typeof__(T) __val; } #endif /* * 7.17.2 Initialization. */ #if defined(__CLANG_ATOMICS) #define ATOMIC_VAR_INIT(value) (value) #define atomic_init(obj, value) __c11_atomic_init(obj, value) #else #define ATOMIC_VAR_INIT(value) { .__val = (value) } #define atomic_init(obj, value) do { \ (obj)->__val = (value); \ } while (0) #endif /* * Clang and recent GCC both provide predefined macros for the memory * orderings. If we are using a compiler that doesn't define them, use the * clang values - these will be ignored in the fallback path. */ #ifndef __ATOMIC_RELAXED #define __ATOMIC_RELAXED 0 #endif #ifndef __ATOMIC_CONSUME #define __ATOMIC_CONSUME 1 #endif #ifndef __ATOMIC_ACQUIRE #define __ATOMIC_ACQUIRE 2 #endif #ifndef __ATOMIC_RELEASE #define __ATOMIC_RELEASE 3 #endif #ifndef __ATOMIC_ACQ_REL #define __ATOMIC_ACQ_REL 4 #endif #ifndef __ATOMIC_SEQ_CST #define __ATOMIC_SEQ_CST 5 #endif /* * 7.17.3 Order and consistency. * * The memory_order_* constants that denote the barrier behaviour of the * atomic operations. */ enum memory_order { memory_order_relaxed = __ATOMIC_RELAXED, memory_order_consume = __ATOMIC_CONSUME, memory_order_acquire = __ATOMIC_ACQUIRE, memory_order_release = __ATOMIC_RELEASE, memory_order_acq_rel = __ATOMIC_ACQ_REL, memory_order_seq_cst = __ATOMIC_SEQ_CST }; typedef enum memory_order memory_order; /* * 7.17.4 Fences. */ #ifdef __CLANG_ATOMICS #define atomic_thread_fence(order) __c11_atomic_thread_fence(order) #define atomic_signal_fence(order) __c11_atomic_signal_fence(order) #elif defined(__GNUC_ATOMICS) #define atomic_thread_fence(order) __atomic_thread_fence(order) #define atomic_signal_fence(order) __atomic_signal_fence(order) #else #define atomic_thread_fence(order) __sync_synchronize() #define atomic_signal_fence(order) __asm volatile ("" : : : "memory") #endif /* * 7.17.5 Lock-free property. */ #if defined(__CLANG_ATOMICS) #define atomic_is_lock_free(obj) \ __c11_atomic_is_lock_free(sizeof(obj)) #elif defined(__GNUC_ATOMICS) #define atomic_is_lock_free(obj) \ __atomic_is_lock_free(sizeof((obj)->__val)) #else #define atomic_is_lock_free(obj) \ (sizeof((obj)->__val) <= sizeof(void *)) #endif /* * 7.17.6 Atomic integer types. */ typedef _Atomic(_Bool) atomic_bool; typedef _Atomic(char) atomic_char; typedef _Atomic(signed char) atomic_schar; typedef _Atomic(unsigned char) atomic_uchar; typedef _Atomic(short) atomic_short; typedef _Atomic(unsigned short) atomic_ushort; typedef _Atomic(int) atomic_int; typedef _Atomic(unsigned int) atomic_uint; typedef _Atomic(long) atomic_long; typedef _Atomic(unsigned long) atomic_ulong; typedef _Atomic(long long) atomic_llong; typedef _Atomic(unsigned long long) atomic_ullong; #if 0 typedef _Atomic(char16_t) atomic_char16_t; typedef _Atomic(char32_t) atomic_char32_t; #endif typedef _Atomic(wchar_t) atomic_wchar_t; typedef _Atomic(int_least8_t) atomic_int_least8_t; typedef _Atomic(uint_least8_t) atomic_uint_least8_t; typedef _Atomic(int_least16_t) atomic_int_least16_t; typedef _Atomic(uint_least16_t) atomic_uint_least16_t; typedef _Atomic(int_least32_t) atomic_int_least32_t; typedef _Atomic(uint_least32_t) atomic_uint_least32_t; typedef _Atomic(int_least64_t) atomic_int_least64_t; typedef _Atomic(uint_least64_t) atomic_uint_least64_t; typedef _Atomic(int_fast8_t) atomic_int_fast8_t; typedef _Atomic(uint_fast8_t) atomic_uint_fast8_t; typedef _Atomic(int_fast16_t) atomic_int_fast16_t; typedef _Atomic(uint_fast16_t) atomic_uint_fast16_t; typedef _Atomic(int_fast32_t) atomic_int_fast32_t; typedef _Atomic(uint_fast32_t) atomic_uint_fast32_t; typedef _Atomic(int_fast64_t) atomic_int_fast64_t; typedef _Atomic(uint_fast64_t) atomic_uint_fast64_t; typedef _Atomic(intptr_t) atomic_intptr_t; typedef _Atomic(uintptr_t) atomic_uintptr_t; typedef _Atomic(size_t) atomic_size_t; typedef _Atomic(ptrdiff_t) atomic_ptrdiff_t; typedef _Atomic(intmax_t) atomic_intmax_t; typedef _Atomic(uintmax_t) atomic_uintmax_t; /* * 7.17.7 Operations on atomic types. */ /* * Compiler-specific operations. */ #if defined(__CLANG_ATOMICS) #define atomic_compare_exchange_strong_explicit(object, expected, \ desired, success, failure) \ __c11_atomic_compare_exchange_strong(object, expected, desired, \ success, failure) #define atomic_compare_exchange_weak_explicit(object, expected, \ desired, success, failure) \ __c11_atomic_compare_exchange_weak(object, expected, desired, \ success, failure) #define atomic_exchange_explicit(object, desired, order) \ __c11_atomic_exchange(object, desired, order) #define atomic_fetch_add_explicit(object, operand, order) \ __c11_atomic_fetch_add(object, operand, order) #define atomic_fetch_and_explicit(object, operand, order) \ __c11_atomic_fetch_and(object, operand, order) #define atomic_fetch_or_explicit(object, operand, order) \ __c11_atomic_fetch_or(object, operand, order) #define atomic_fetch_sub_explicit(object, operand, order) \ __c11_atomic_fetch_sub(object, operand, order) #define atomic_fetch_xor_explicit(object, operand, order) \ __c11_atomic_fetch_xor(object, operand, order) #define atomic_load_explicit(object, order) \ __c11_atomic_load(object, order) #define atomic_store_explicit(object, desired, order) \ __c11_atomic_store(object, desired, order) #elif defined(__GNUC_ATOMICS) #define atomic_compare_exchange_strong_explicit(object, expected, \ desired, success, failure) \ __atomic_compare_exchange_n(&(object)->__val, expected, \ desired, 0, success, failure) #define atomic_compare_exchange_weak_explicit(object, expected, \ desired, success, failure) \ __atomic_compare_exchange_n(&(object)->__val, expected, \ desired, 1, success, failure) #define atomic_exchange_explicit(object, desired, order) \ __atomic_exchange_n(&(object)->__val, desired, order) #define atomic_fetch_add_explicit(object, operand, order) \ __atomic_fetch_add(&(object)->__val, operand, order) #define atomic_fetch_and_explicit(object, operand, order) \ __atomic_fetch_and(&(object)->__val, operand, order) #define atomic_fetch_or_explicit(object, operand, order) \ __atomic_fetch_or(&(object)->__val, operand, order) #define atomic_fetch_sub_explicit(object, operand, order) \ __atomic_fetch_sub(&(object)->__val, operand, order) #define atomic_fetch_xor_explicit(object, operand, order) \ __atomic_fetch_xor(&(object)->__val, operand, order) #define atomic_load_explicit(object, order) \ __atomic_load_n(&(object)->__val, order) #define atomic_store_explicit(object, desired, order) \ __atomic_store_n(&(object)->__val, desired, order) #else #define atomic_compare_exchange_strong_explicit(object, expected, \ desired, success, failure) ({ \ __typeof__((object)->__val) __v; \ _Bool __r; \ __v = __sync_val_compare_and_swap(&(object)->__val, \ *(expected), desired); \ __r = *(expected) == __v; \ *(expected) = __v; \ __r; \ }) #define atomic_compare_exchange_weak_explicit(object, expected, \ desired, success, failure) \ atomic_compare_exchange_strong_explicit(object, expected, \ desired, success, failure) #if __has_builtin(__sync_swap) /* Clang provides a full-barrier atomic exchange - use it if available. */ #define atomic_exchange_explicit(object, desired, order) \ __sync_swap(&(object)->__val, desired) #else /* * __sync_lock_test_and_set() is only an acquire barrier in theory (although in * practice it is usually a full barrier) so we need an explicit barrier after * it. */ #define atomic_exchange_explicit(object, desired, order) ({ \ __typeof__((object)->__val) __v; \ __v = __sync_lock_test_and_set(&(object)->__val, desired); \ __sync_synchronize(); \ __v; \ }) #endif #define atomic_fetch_add_explicit(object, operand, order) \ __sync_fetch_and_add(&(object)->__val, operand) #define atomic_fetch_and_explicit(object, operand, order) \ __sync_fetch_and_and(&(object)->__val, operand) #define atomic_fetch_or_explicit(object, operand, order) \ __sync_fetch_and_or(&(object)->__val, operand) #define atomic_fetch_sub_explicit(object, operand, order) \ __sync_fetch_and_sub(&(object)->__val, operand) #define atomic_fetch_xor_explicit(object, operand, order) \ __sync_fetch_and_xor(&(object)->__val, operand) #define atomic_load_explicit(object, order) \ __sync_fetch_and_add(&(object)->__val, 0) #define atomic_store_explicit(object, desired, order) do { \ __sync_synchronize(); \ (object)->__val = (desired); \ __sync_synchronize(); \ } while (0) #endif /* * Convenience functions. */ #define atomic_compare_exchange_strong(object, expected, desired) \ atomic_compare_exchange_strong_explicit(object, expected, \ desired, memory_order_seq_cst, memory_order_seq_cst) #define atomic_compare_exchange_weak(object, expected, desired) \ atomic_compare_exchange_weak_explicit(object, expected, \ desired, memory_order_seq_cst, memory_order_seq_cst) #define atomic_exchange(object, desired) \ atomic_exchange_explicit(object, desired, memory_order_seq_cst) #define atomic_fetch_add(object, operand) \ atomic_fetch_add_explicit(object, operand, memory_order_seq_cst) #define atomic_fetch_and(object, operand) \ atomic_fetch_and_explicit(object, operand, memory_order_seq_cst) #define atomic_fetch_or(object, operand) \ atomic_fetch_or_explicit(object, operand, memory_order_seq_cst) #define atomic_fetch_sub(object, operand) \ atomic_fetch_sub_explicit(object, operand, memory_order_seq_cst) #define atomic_fetch_xor(object, operand) \ atomic_fetch_xor_explicit(object, operand, memory_order_seq_cst) #define atomic_load(object) \ atomic_load_explicit(object, memory_order_seq_cst) #define atomic_store(object, desired) \ atomic_store_explicit(object, desired, memory_order_seq_cst) /* * 7.17.8 Atomic flag type and operations. */ typedef atomic_bool atomic_flag; #define ATOMIC_FLAG_INIT ATOMIC_VAR_INIT(0) #define atomic_flag_clear_explicit(object, order) \ atomic_store_explicit(object, 0, order) #define atomic_flag_test_and_set_explicit(object, order) \ atomic_compare_exchange_strong_explicit(object, 0, 1, order, order) #define atomic_flag_clear(object) \ atomic_flag_clear_explicit(object, memory_order_seq_cst) #define atomic_flag_test_and_set(object) \ atomic_flag_test_and_set_explicit(object, memory_order_seq_cst) #endif /* !_STDATOMIC_H_ */ ================================================ FILE: subprojects/.gitignore ================================================ h2o-2.2.4 libuv-v1.18.0 peg-0.1.18 protobuf-3.5.0 protobuf-c-1.3.0 wslay-d72ea2ea9e24032144ab85f840e3aaf8cd5d6e07 ================================================ FILE: subprojects/h2o.wrap ================================================ [wrap-file] directory = h2o-2.2.4 source_url = https://github.com/h2o/h2o/archive/v2.2.4.tar.gz source_filename = v2.2.4.tar.gz source_hash = ebacf3b15f40958c950e18e79ad5a647f61e989c6dbfdeea858ce943ef5e3cd8 patch_url = https://fake.url.to.please.meson.but.file.in.packagecache/ patch_filename = h2o-wrap-2.2.4.tar patch_hash = 659b2da9dc17b522dac9a86b67d9295408b036df9e485625bb2382a9ce0a7597 ================================================ FILE: subprojects/libuv.wrap ================================================ [wrap-file] directory = libuv-v1.18.0 source_url = https://dist.libuv.org/dist/v1.18.0/libuv-v1.18.0.tar.gz source_filename = libuv-v1.18.0.tar.gz source_hash = 54e4734da09172f19d5061dcfd7a536fe4c3a8dc12ed981a14a58ac17efdab88 patch_url = https://fake.url.to.please.meson.but.file.in.packagecache/ patch_filename = libuv-wrap-v1.18.0.tar patch_hash = 16f07003a8511e9aa955ef4ca79fcb160d9e66283dce7c26e46c83fd69548f59 ================================================ FILE: subprojects/packagecache/.gitignore ================================================ d72ea2e.tar.gz libuv-v1.18.0.tar.gz peg-0.1.18.tar.gz protobuf-all-3.5.0.tar.gz protobuf-c-1.3.0.tar.gz v2.2.4.tar.gz ================================================ FILE: subprojects/peg.wrap ================================================ [wrap-file] directory = peg-0.1.18 source_url = http://download.openpkg.org/components/cache/peg/peg-0.1.18.tar.gz source_filename = peg-0.1.18.tar.gz source_hash = 20193bdd673fc7487a38937e297fff08aa73751b633a086ac28c3b34890f9084 patch_url = https://fake.url.to.please.meson.but.file.in.packagecache/ patch_filename = peg-wrap-0.1.18.tar patch_hash = c5cb8913fca3ed4a3af467c822d719107b66da6b2593b1432148b4dd6f5b5bb1 ================================================ FILE: subprojects/protobuf-c.wrap ================================================ [wrap-file] directory = protobuf-c-1.3.0 source_url = https://github.com/protobuf-c/protobuf-c/releases/download/v1.3.0/protobuf-c-1.3.0.tar.gz source_filename = protobuf-c-1.3.0.tar.gz source_hash = 5dc9ad7a9b889cf7c8ff6bf72215f1874a90260f60ad4f88acf21bb15d2752a1 patch_url = https://fake.url.to.please.meson.but.file.in.packagecache/ patch_filename = protobuf-c-wrap-1.3.0.tar patch_hash = cdaf6932f5e7e20f7f1cfd37a25a91a223a4eced8d60c4fe2112569b381040f8 ================================================ FILE: subprojects/protobuf.wrap ================================================ [wrap-file] directory = protobuf-3.5.0 source_url = https://github.com/google/protobuf/releases/download/v3.5.0/protobuf-all-3.5.0.tar.gz source_filename = protobuf-all-3.5.0.tar.gz source_hash = 5c3e0b369e767993969fdebcb3f44cbddd7fdd86644a926780daab46341d10a7 patch_url = https://fake.url.to.please.meson.but.file.in.packagecache/ patch_filename = protobuf-wrap-3.5.0.tar patch_hash = 47b41bcdc5bfb634405c5fd5b8adc7773fc99056e48d6155069f49e87dfe2a3b ================================================ FILE: subprojects/wslay.wrap ================================================ [wrap-file] directory = wslay-d72ea2ea9e24032144ab85f840e3aaf8cd5d6e07 source_url = https://github.com/djdeath/wslay/archive/d72ea2e.tar.gz source_filename = d72ea2e.tar.gz source_hash = 75f282ae17ef3f59b99279a5ace9830da0fad66bcfa88f878a60a009eb193450 patch_url = https://fake.url.to.please.meson.but.file.in.packagecache/ patch_filename = wslay-wrap.tar patch_hash = ea9f31b957f95a1ffdfbd4e4d83aeb5fe6e58cf4b3b2f512d77efa28d2707407 ================================================ FILE: ui/gputop-emscripten-network.c ================================================ /* * GPU Top * * Copyright (C) 2018 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "gputop-network.h" #include struct _gputop_connection_t { int websocket; bool connected; gputop_on_ready_cb_t ready_cb; gputop_on_data_cb_t data_cb; gputop_on_close_cb_t close_cb; void *user_data; }; static void gputop_connection_free(gputop_connection_t *conn) { free(conn); } EMSCRIPTEN_KEEPALIVE static void gputop_emscripten_network_on_message(gputop_connection_t *conn, const void *data, size_t length) { conn->data_cb(conn, data, length, conn->user_data); } EMSCRIPTEN_KEEPALIVE static void gputop_emscripten_network_on_close(gputop_connection_t *conn, int code, const char *message) { conn->connected = false; conn->close_cb(conn, code != 1000 ? message : NULL, conn->user_data); gputop_connection_free(conn); } EMSCRIPTEN_KEEPALIVE static void gputop_emscripten_network_on_open(gputop_connection_t *conn) { conn->connected = true; conn->ready_cb(conn, conn->user_data); } gputop_connection_t * gputop_connect(const char *host, int port, gputop_on_ready_cb_t ready_cb, gputop_on_data_cb_t data_cb, gputop_on_close_cb_t close_cb, void *user_data) { gputop_connection_t *conn = calloc(1, sizeof(gputop_connection_t)); conn->ready_cb = ready_cb; conn->data_cb = data_cb; conn->close_cb = close_cb; conn->websocket = EM_ASM_INT({ if (Module['_gputop_websockets'] === undefined) { Module['_gputop_websockets'] = {}; Module['_gputop_websockets_id'] = 1; } var url = 'ws://' + Pointer_stringify($1) + ':' + $2 + '/gputop'; var ws = new WebSocket(url, 'binary'); console.log('Connecting to ' + url); ws.binaryType = 'arraybuffer'; var id = Module['_gputop_websockets_id']; Module['_gputop_websockets_id'] += 1; Module['_gputop_websockets'][id] = ws; ws.onopen = function() { Module['_gputop_emscripten_network_on_open']($0); }; ws.onclose = function(event) { console.log('close code='+ event.code + ' message=' + event.reason); Module['_gputop_emscripten_network_on_close']( $0, event.code, event.reason); }; ws.onmessage = function(event) { if (event.data instanceof ArrayBuffer) { ccall('gputop_emscripten_network_on_message', null, ['number', 'array', 'number'], [$0, new Uint8Array(event.data), event.data.byteLength]); } else console.error('Unable to handle WebSocket message', event.data); }; return id; }, conn, host, port); return conn; } void gputop_connection_send(gputop_connection_t *conn, const void *data, size_t len) { if (conn == NULL || conn->websocket == 0 || data == NULL || len == 0) return; EM_ASM_INT({ var ws = Module['_gputop_websockets'][$0]; if (ws === undefined) return; var bytes = new Uint8Array(Module.HEAPU8.buffer, $1, $2); ws.send(bytes); }, conn->websocket, data, len); } void gputop_connection_close(gputop_connection_t *conn) { if (conn == NULL) return; EM_ASM({ var ws = Module['_gputop_websockets'][$0]; if (ws === undefined) return; ws.close(); }, conn->websocket); } bool gputop_connection_connected(gputop_connection_t *conn) { if (!conn || !conn->websocket) return false; return conn->connected; } ================================================ FILE: ui/gputop-soup-network.c ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "gputop-network.h" #include struct _gputop_connection_t { SoupSession *session; SoupWebsocketConnection *conn; GCancellable *cancel; gputop_on_ready_cb_t ready_cb; gputop_on_data_cb_t data_cb; gputop_on_close_cb_t close_cb; void *user_data; }; static void gputop_connection_free(gputop_connection_t *conn) { g_clear_pointer(&conn->conn, g_object_unref); g_clear_pointer(&conn->session, g_object_unref); g_clear_pointer(&conn->cancel, g_object_unref); g_free(conn); } static void on_websocket_message(SoupWebsocketConnection *self, gint type, GBytes *message, gpointer user_data) { gputop_connection_t *conn = user_data; conn->data_cb(conn, g_bytes_get_data(message, NULL), g_bytes_get_size(message), conn->user_data); } static void on_websocket_closed(SoupWebsocketConnection *self, gpointer user_data) { gputop_connection_t *conn = user_data; conn->close_cb(conn, NULL, conn->user_data); gputop_connection_free(conn); } static void on_websocket_ready(GObject *source_object, GAsyncResult *res, gpointer user_data) { gputop_connection_t *conn = user_data; GError *error = NULL; conn->conn = soup_session_websocket_connect_finish(conn->session, res, &error); if (error) { conn->close_cb(conn, error->message, conn->user_data); g_error_free(error); gputop_connection_free(conn); return; } g_signal_connect(conn->conn, "message", G_CALLBACK(on_websocket_message), conn); g_signal_connect(conn->conn, "closed", G_CALLBACK(on_websocket_closed), conn); conn->ready_cb(conn, conn->user_data); } gputop_connection_t * gputop_connect(const char *host, int port, gputop_on_ready_cb_t ready_cb, gputop_on_data_cb_t data_cb, gputop_on_close_cb_t close_cb, void *user_data) { gputop_connection_t *conn = g_new0(gputop_connection_t, 1); conn->ready_cb = ready_cb; conn->data_cb = data_cb; conn->close_cb = close_cb; gchar *url = g_strdup_printf("ws://%s:%u/gputop/", host, port); SoupMessage *msg = soup_message_new("GET", url); g_free(url); conn->session = soup_session_new(); g_object_set(conn->session, "proxy-resolver", NULL, NULL); conn->cancel = g_cancellable_new(); soup_session_websocket_connect_async(conn->session, msg, NULL, NULL, conn->cancel, on_websocket_ready, conn); return conn; } void gputop_connection_send(gputop_connection_t *conn, const void *data, size_t len) { g_return_if_fail(conn != NULL); g_return_if_fail(conn->conn != NULL); g_return_if_fail(data != NULL && len != 0); soup_websocket_connection_send_binary(conn->conn, data, len); } void gputop_connection_close(gputop_connection_t *conn) { g_return_if_fail(conn != NULL); if (conn->conn) soup_websocket_connection_close(conn->conn, 0, ""); else g_cancellable_cancel(conn->cancel); } bool gputop_connection_connected(gputop_connection_t *conn) { g_return_val_if_fail(conn != NULL, false); if (!conn->conn) return false; return true; } ================================================ FILE: ui/gputop-ui-main.cpp ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include "imgui.h" #include "gputop-ui-multilines.h" #include "gputop-ui-piechart.h" #include "gputop-ui-plots.h" #include "gputop-ui-timeline.h" #include "gputop-ui-topology.h" #include "gputop-ui-utils.h" #include "util/hash_table.h" #include "util/list.h" #include "gputop-client-context.h" #include "gputop-util.h" #ifdef EMSCRIPTEN #include "imgui_impl_sdl_gles2.h" #include #include #include #include #define ImGui_ScheduleFrame() ImGui_ImplSdlGLES2_ScheduleFrame() #define ImGui_RenderDrawData(data) ImGui_ImplSdlGLES2_RenderDrawData() #elif defined(GPUTOP_UI_GTK) #include "imgui_impl_gtk3_cogl.h" #include #define ImGui_ScheduleFrame() ImGui_ImplGtk3Cogl_ScheduleFrame() #define ImGui_RenderDrawData(data) ImGui_ImplGtk3Cogl_RenderDrawData(data) #elif defined(GPUTOP_UI_GLFW) #include "imgui_impl_glfw_gl3.h" #include #include #include #include #define ImGui_ScheduleFrame() ImGui_ImplGlfwGL3_ScheduleFrame() #define ImGui_RenderDrawData(data) ImGui_ImplGlfwGL3_RenderDrawData(data) #endif /**/ struct window { struct list_head link; char name[128]; bool opened; ImVec2 position; ImVec2 size; void (*display)(struct window*); void (*destroy)(struct window*); }; struct i915_perf_window_counter { struct list_head link; const struct gputop_metric_set_counter *counter; bool use_samples_max; }; struct i915_perf_window { struct window base; struct list_head link; struct list_head counters; }; struct timeline_window { struct window base; uint64_t zoom_start, zoom_length; struct gputop_accumulated_samples selected_sample; struct gputop_hw_context selected_context; char timestamp_search[40]; int64_t searched_timestamp; char gt_timestamp_range[100]; uint32_t n_accumulated_reports; int32_t hovered_report; float *accumulated_values; struct gputop_perf_tracepoint tracepoint; uint64_t tracepoint_selected_ts; struct window counters_window; struct window events_window; struct window reports_window; struct window report_window; struct window usage_window; /**/ char gt_timestamp_highlight_str[100]; uint64_t gt_timestamp_highlight; /* List of timestamps to display on the timeline */ char gt_timestamps_list[1024]; uint64_t gt_timestamps_display[100]; int n_gt_timestamps_display; /* Used when timestamp correlation is not possible */ uint64_t zoom_tp_start, zoom_tp_length; }; static struct { char host_address[128]; int host_port; gputop_connection_t *connection; char *connection_error; gputop_client_context ctx; struct { char *msg; } messages[100]; int start_message; int n_messages; int n_cpu_colors; ImColor cpu_colors[100]; /* UI */ struct list_head windows; struct window main_window; struct window log_window; struct window style_editor_window; struct window report_window; struct window streams_window; struct window tracepoints_window; struct timeline_window timeline_window; struct i915_perf_window global_i915_perf_window; struct i915_perf_window contexts_i915_perf_window; struct window live_i915_perf_counters_window; struct window live_i915_perf_usage_window; ImVec4 clear_color; /**/ void *temporary_buffer; size_t temporary_buffer_size; #ifdef EMSCRIPTEN SDL_Window *window; #elif defined(GPUTOP_UI_GLFW) GLFWwindow *window; #endif } context; /**/ static void hide_window(struct window *win) { /* NOP */ } static void toggle_show_window(struct window *win) { if (win->opened) win->opened = false; else { win->opened = true; list_add(&win->link, &context.windows); } } /**/ static void * ensure_temporary_buffer(size_t size) { if (context.temporary_buffer_size < size) { context.temporary_buffer_size = size; context.temporary_buffer = realloc(context.temporary_buffer, size); } return context.temporary_buffer; } #define ensure_plot_accumulator(n_plot) \ ((float *) ensure_temporary_buffer(n_plot * sizeof(float))) #define ensure_timeline_names(n_names) \ ((char **) ensure_temporary_buffer(n_names * sizeof(char *))) /**/ extern "C" void gputop_cr_console_log(const char *format, ...) { va_list ap; char str[1024]; int l; va_start(ap, format); l = snprintf(str, sizeof(str), "CLIENT: "); vsnprintf(&str[l], sizeof(str) - l, format, ap); va_end(ap); if (context.n_messages < ARRAY_SIZE(context.messages)) { context.messages[context.n_messages].msg = strdup(str); context.n_messages++; } else { int idx = (++context.start_message + context.n_messages) % ARRAY_SIZE(context.messages); free(context.messages[idx].msg); context.messages[idx].msg = strdup(str); } } static void clear_client_logs(void) { for (int i = 0; i < context.n_messages; i++) free(context.messages[i].msg); context.start_message = context.n_messages = 0; } /**/ static bool StartStopSamplingButton(struct gputop_client_context *ctx) { return ImGui::Button(ctx->is_sampling ? "Stop sampling" : "Start sampling") && ctx->metric_set; } static void toggle_start_stop_sampling(struct gputop_client_context *ctx) { if (ctx->is_sampling) gputop_client_context_stop_sampling(ctx); else gputop_client_context_start_sampling(ctx); } /**/ static void update_cpu_colors(int n_cpus) { for (int cpu = 0; cpu < n_cpus; cpu++) { float r, g, b; ImGui::ColorConvertHSVtoRGB(cpu * 1.0f / n_cpus, 1.0f, 1.0f, r, g, b); context.cpu_colors[cpu] = ImColor(r, g, b); } context.n_cpu_colors = n_cpus; } static void on_connection_data(gputop_connection_t *conn, const void *payload, size_t payload_len, void *user_data) { struct gputop_client_context *ctx = &context.ctx; gputop_client_context_handle_data(ctx, payload, payload_len); if (ctx->features && context.n_cpu_colors != ctx->features->features->n_cpus) update_cpu_colors(ctx->features->features->n_cpus); ImGui_ScheduleFrame(); } static void on_connection_closed(gputop_connection_t *conn, const char *error, void *user_data) { free(context.connection_error); context.connection_error = NULL; if (error) context.connection_error = strdup(error); else context.connection_error = strdup("Disconnected"); context.ctx.connection = NULL; } static void on_connection_ready(gputop_connection_t *conn, void *user_data) { context.connection = conn; clear_client_logs(); gputop_client_context_reset(&context.ctx, conn); } static void reconnect(void) { struct gputop_client_context *ctx = &context.ctx; if (ctx->connection) gputop_connection_close(ctx->connection); free(context.connection_error); context.connection_error = NULL; ctx->connection = gputop_connect(context.host_address, context.host_port, on_connection_ready, on_connection_data, on_connection_closed, NULL); } /**/ static void pretty_print_counter_value(const struct gputop_metric_set_counter *counter, double value, char *buffer, size_t length) { gputop_client_pretty_print_value(counter->units, value, buffer, length); } static double read_counter_max(struct gputop_client_context *ctx, struct gputop_accumulated_samples *sample, const struct gputop_metric_set_counter *counter, float max_value) { switch (counter->data_type) { case GPUTOP_PERFQUERY_COUNTER_DATA_UINT64: case GPUTOP_PERFQUERY_COUNTER_DATA_UINT32: case GPUTOP_PERFQUERY_COUNTER_DATA_BOOL32: if (counter->max_uint64) return counter->max_uint64(&ctx->devinfo, ctx->metric_set, sample->accumulator.deltas); break; case GPUTOP_PERFQUERY_COUNTER_DATA_DOUBLE: case GPUTOP_PERFQUERY_COUNTER_DATA_FLOAT: if (counter->max_float) return counter->max_float(&ctx->devinfo, ctx->metric_set, sample->accumulator.deltas); break; } return max_value; } static void add_counter_i915_perf_window(struct i915_perf_window *window, const struct gputop_metric_set_counter *counter) { struct i915_perf_window_counter *c = (struct i915_perf_window_counter *) calloc(1, sizeof(*c)); c->counter = counter; list_addtail(&c->link, &window->counters); } static void display_i915_perf_counters(struct gputop_client_context *ctx, ImGuiTextFilter *filter, struct gputop_accumulated_samples *samples, bool add_buttons) { if (!ctx->metric_set) { ImGui::Text("No metric set selected"); return; } for (int c = 0; c < ctx->metric_set->n_counters; c++) { const struct gputop_metric_set_counter *counter = &ctx->metric_set->counters[c]; if (!filter->PassFilter(counter->name)) continue; if (add_buttons) { ImGui::PushID(counter); if (ImGui::Button("+")) { if (context.global_i915_perf_window.base.opened) add_counter_i915_perf_window(&context.global_i915_perf_window, counter); if (context.contexts_i915_perf_window.base.opened) add_counter_i915_perf_window(&context.contexts_i915_perf_window, counter); } ImGui::SameLine(); ImGui::PopID(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Add counter to timeline windows"); } double value = samples ? gputop_client_context_read_counter_value(ctx, samples, counter) : 0.0f; double max = samples ? read_counter_max(ctx, samples, counter, MAX2(1.0f, value)) : 1.0f; ImGui::ProgressBar(value / max, ImVec2(100, 0)); ImGui::SameLine(); char text[100]; if (ImGui::IsItemHovered()) { gputop_client_context_pretty_print_max(ctx, counter, ctx->oa_aggregation_period_ns, text, sizeof(text)); ImGui::SetTooltip("Maximum : %s", text); } pretty_print_counter_value(counter, value, text, sizeof(text)); ImGui::Text("%s : %s", counter->name, text); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("%s", counter->desc); } } } static void display_live_i915_perf_counters_window(struct window *win) { struct gputop_client_context *ctx = &context.ctx; ImGui::Text("Metric set: %s", ctx->metric_set ? ctx->metric_set->name : ""); static ImGuiTextFilter filter; filter.Draw(); if (!ctx->metric_set) return; struct gputop_accumulated_samples *last_sample = list_empty(&ctx->graphs) ? NULL : list_last_entry(&ctx->graphs, struct gputop_accumulated_samples, link); ImGui::BeginChild("##counters"); display_i915_perf_counters(ctx, &filter, last_sample, true); ImGui::EndChild(); } static void show_live_i915_perf_counters_window(void) { struct window *window = &context.live_i915_perf_counters_window; if (window->opened) { window->opened = false; return; } snprintf(window->name, sizeof(window->name), "i915 perf counters (live)##%p", window); window->size = ImVec2(400, 600); window->display = display_live_i915_perf_counters_window; window->destroy = hide_window; window->opened = true; list_add(&window->link, &context.windows); } static void display_live_i915_perf_usage_window(struct window *win) { struct gputop_client_context *ctx = &context.ctx; ImVec2 pb_size(ImGui::GetWindowContentRegionWidth() * 2.0f / 3.0f, 0); double idle = 1.0f; list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { ImGui::ProgressBar(context->usage_percent, pb_size); ImGui::SameLine(); ImGui::Text("%s", context->name); idle -= context->usage_percent; } ImGui::ProgressBar(idle, pb_size); ImGui::SameLine(); ImGui::Text("Idle"); } static void show_live_i915_perf_usage_window(void) { struct window *window = &context.live_i915_perf_usage_window; if (window->opened) { window->opened = false; return; } snprintf(window->name, sizeof(window->name), "i915 perf usage (live)##%p", window); window->size = ImVec2(400, 300); window->display = display_live_i915_perf_usage_window; window->destroy = hide_window; window->opened = true; list_add(&window->link, &context.windows); } /**/ static float * get_counter_samples(struct gputop_client_context *ctx, int max_graphs, struct gputop_accumulated_samples *first_samples, struct i915_perf_window_counter *counter, float *max_value) { float *values = ensure_plot_accumulator(max_graphs); int i; for (i = 0; i < (max_graphs - ctx->n_graphs); i++) values[i] = 0.0f; *max_value = 0.0f; struct gputop_accumulated_samples *sample = first_samples; for (; i < max_graphs; i++) { values[i] = gputop_client_context_read_counter_value(ctx, sample, counter->counter); *max_value = MAX2(*max_value, values[i]); sample = list_first_entry(&sample->link, struct gputop_accumulated_samples, link); } return values; } static void remove_counter_i915_perf_window(struct i915_perf_window_counter *counter) { list_del(&counter->link); free(counter); } static bool select_i915_perf_counter(struct gputop_client_context *ctx, const struct gputop_metric_set_counter **out_counter) { bool selected = false; static ImGuiTextFilter filter; filter.Draw(); if (!ctx->metric_set) return false; struct gputop_accumulated_samples *last_sample = list_last_entry(&ctx->graphs, struct gputop_accumulated_samples, link); ImGui::BeginChild("##block", ImVec2(0, 300)); for (int c = 0; c < ctx->metric_set->n_counters; c++) { bool hovered; const struct gputop_metric_set_counter *counter = &ctx->metric_set->counters[c]; if (!filter.PassFilter(counter->name)) continue; if (ImGui::Selectable(counter->name)) { *out_counter = counter; selected = true; } hovered = ImGui::IsItemHovered(); double value = gputop_client_context_read_counter_value(ctx, last_sample, counter); ImGui::ProgressBar(value / read_counter_max(ctx, last_sample, counter, MAX2(1.0f, value)), ImVec2(100, 0)); ImGui::SameLine(); char svalue[100]; pretty_print_counter_value(counter, value, svalue, sizeof(svalue)); if (ImGui::Selectable(svalue, hovered)) { *out_counter = counter; selected = true; } } ImGui::EndChild(); return selected; } static void cleanup_counters_i915_perf_window(struct i915_perf_window *window) { list_for_each_entry_safe(struct i915_perf_window_counter, c, &window->counters, link) { list_del(&c->link); free(c); } } static void display_global_i915_perf_window(struct window *win) { struct i915_perf_window *window = (struct i915_perf_window *) win; struct gputop_client_context *ctx = &context.ctx; uint32_t max_graphs = (ctx->oa_visible_timeline_s * 1000000000.0f) / ctx->oa_aggregation_period_ns; bool open_popup = ImGui::Button("Select counters"); if (open_popup) ImGui::OpenPopup("counter picker"); if (ImGui::BeginPopup("counter picker")) { const struct gputop_metric_set_counter *counter = NULL; if (select_i915_perf_counter(ctx, &counter)) add_counter_i915_perf_window(window, counter); ImGui::EndPopup(); } ImGui::SameLine(); if (ImGui::Button("Clear counters")) { cleanup_counters_i915_perf_window(window); } ImGui::SameLine(); if (StartStopSamplingButton(ctx)) { toggle_start_stop_sampling(ctx); } if (ctx->n_graphs < max_graphs) { ImGui::SameLine(); ImGui::Text("Loading:"); ImGui::SameLine(); ImGui::ProgressBar((float) ctx->n_graphs / max_graphs); } ImGui::BeginChild("##block"); list_for_each_entry_safe(struct i915_perf_window_counter, c, &window->counters, link) { /* Hide previous selected counters on metric set that isn't * currently used. */ if (c->counter->metric_set != ctx->metric_set) continue; ImGui::Text("%s", c->counter->desc); ImGui::PushID(c); if (ImGui::Button("X")) { remove_counter_i915_perf_window(c); } ImGui::PopID(); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("Remove counter"); } ImGui::SameLine(); ImGui::PushID(c); if (ImGui::Button("M")) { c->use_samples_max ^= 1; } ImGui::PopID(); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("Change max behavior"); } ImGui::SameLine(); struct gputop_accumulated_samples *first_samples = list_first_entry(&ctx->graphs, struct gputop_accumulated_samples, link); float max_value = 0.0f; const float *values = get_counter_samples(ctx, max_graphs, first_samples, c, &max_value); int hovered = Gputop::PlotLines("", values, max_graphs, 0, -1, c->counter->name, 0, c->use_samples_max ? max_value : read_counter_max(ctx, first_samples, c->counter, max_value), ImVec2(ImGui::GetContentRegionAvailWidth() - 10, 50.0f)); if (hovered >= 0) { char tooltip_tex[100]; pretty_print_counter_value(c->counter, values[hovered], tooltip_tex, sizeof(tooltip_tex)); ImGui::SetTooltip("%s", tooltip_tex); } } ImGui::EndChild(); } static void show_global_i915_perf_window(void) { struct i915_perf_window *window = &context.global_i915_perf_window; if (window->base.opened) { window->base.opened = false; return; } snprintf(window->base.name, sizeof(window->base.name), "i915 perf counters (timeline)##%p", window); window->base.size = ImVec2(400, 600); window->base.display = display_global_i915_perf_window; window->base.destroy = hide_window; window->base.opened = true; list_inithead(&window->counters); list_add(&window->base.link, &context.windows); } /**/ static void select_hw_contexts(struct gputop_client_context *ctx) { list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { if (ImGui::Selectable(context->name, context->selected)) { context->selected = context->selected ? false : true; } } } static void display_contexts_i915_perf_window(struct window *win) { struct i915_perf_window *window = (struct i915_perf_window *) win; struct gputop_client_context *ctx = &context.ctx; uint32_t max_graphs = (ctx->oa_visible_timeline_s * 1000000000.0f) / ctx->oa_aggregation_period_ns; bool open_popup = ImGui::Button("Select contexts"); if (open_popup) ImGui::OpenPopup("context picker"); if (ImGui::BeginPopup("context picker")) { select_hw_contexts(ctx); ImGui::EndPopup(); } ImGui::SameLine(); open_popup = ImGui::Button("Select counters"); if (open_popup) ImGui::OpenPopup("counter picker"); if (ImGui::BeginPopup("counter picker")) { const struct gputop_metric_set_counter *counter = NULL; if (select_i915_perf_counter(ctx, &counter)) add_counter_i915_perf_window(window, counter); ImGui::EndPopup(); } ImGui::SameLine(); if (ImGui::Button("Clear counters")) { cleanup_counters_i915_perf_window(window); } ImGui::SameLine(); if (StartStopSamplingButton(ctx)) { toggle_start_stop_sampling(ctx); } if (ctx->n_graphs < max_graphs) { ImGui::SameLine(); ImGui::Text("Loading:"); ImGui::SameLine(); ImGui::ProgressBar((float) ctx->n_graphs / max_graphs); } ImGui::BeginChild("##block"); list_for_each_entry_safe(struct i915_perf_window_counter, c, &window->counters, link) { /* Hide previous selected counters on metric set that isn't * currently used. */ if (c->counter->metric_set != ctx->metric_set) continue; ImGui::PushID(c); if (ImGui::Button("X")) { remove_counter_i915_perf_window(c); } ImGui::PopID(); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("Remove counter"); } ImGui::SameLine(); ImGui::PushID(c); if (ImGui::Button("M")) { c->use_samples_max ^= 1; } ImGui::PopID(); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("Change max behavior"); } ImGui::SameLine(); ImGui::Text("%s", c->counter->name); list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { if (!context->selected) continue; ImGui::Text("%s", context->name); struct gputop_accumulated_samples *first_samples = list_first_entry(&context->graphs, struct gputop_accumulated_samples, link); float max_value = 0.0f; const float *values = get_counter_samples(ctx, max_graphs, first_samples, c, &max_value); int hovered = Gputop::PlotLines("", values, max_graphs, 0, -1, "", 0, c->use_samples_max ? max_value : read_counter_max(ctx, first_samples, c->counter, max_value), ImVec2(ImGui::GetContentRegionAvailWidth() - 10, 50.0f)); if (hovered >= 0 ) { char tooltip_tex[100]; pretty_print_counter_value(c->counter, values[hovered], tooltip_tex, sizeof(tooltip_tex)); ImGui::SetTooltip("%s", tooltip_tex); } } } ImGui::EndChild(); } static void show_contexts_i915_perf_window(void) { struct i915_perf_window *window = &context.contexts_i915_perf_window; if (window->base.opened) { window->base.opened = false; return; } snprintf(window->base.name, sizeof(window->base.name), "Per context i915 perf counters (timeline)##%p", window); window->base.size = ImVec2(400, 600); window->base.display = display_contexts_i915_perf_window; window->base.destroy = hide_window; window->base.opened = true; list_inithead(&window->counters); list_add(&window->base.link, &context.windows); } /**/ // static void // display_accumulated_reports(struct gputop_client_context *ctx, // struct gputop_accumulated_samples *samples, // bool default_opened) // { // struct gputop_record_iterator iter; // ImGui::BeginChild("##reports"); // gputop_record_iterator_init(&iter, samples); // while (gputop_record_iterator_next(&iter)) { // switch (iter.header->type) { // case DRM_I915_PERF_RECORD_OA_BUFFER_LOST: // ImGui::Text("OA buffer lost"); // break; // case DRM_I915_PERF_RECORD_OA_REPORT_LOST: // ImGui::Text("OA report lost"); // break; // case DRM_I915_PERF_RECORD_SAMPLE: { // const uint64_t *cpu_timestamp = (const uint64_t *) // gputop_i915_perf_record_field(&ctx->i915_perf_config, iter.header, // GPUTOP_I915_PERF_FIELD_CPU_TIMESTAMP); // const uint64_t *gpu_timestamp = (const uint64_t *) // gputop_i915_perf_record_field(&ctx->i915_perf_config, iter.header, // GPUTOP_I915_PERF_FIELD_GPU_TIMESTAMP); // const uint8_t *report = (const uint8_t *) // gputop_i915_perf_record_field(&ctx->i915_perf_config, iter.header, // GPUTOP_I915_PERF_FIELD_OA_REPORT); // ImGui::Text("rcs=%08" PRIx64 "(%" PRIx64 " scaled) rcs64=%016" PRIx64 // " cpu=%" PRIx64 " id=0x%x reason=%s", // gputop_cc_oa_report_get_timestamp(report), // gputop_timebase_scale_ns(&ctx->devinfo, // gputop_cc_oa_report_get_timestamp(report)), // gpu_timestamp ? *gpu_timestamp : 0UL, // cpu_timestamp ? *cpu_timestamp : 0UL, // gputop_cc_oa_report_get_ctx_id(&ctx->devinfo, report), // gputop_cc_oa_report_get_reason(&ctx->devinfo, report)); // break; // } // default: // ImGui::Text("i915 perf: Spurious header type = %d", iter.header->type); // iter.done = true; // break; // } // } // ImGui::EndChild(); // } static void display_report_window(struct window *win) { struct gputop_client_context *ctx = &context.ctx; ImGui::Columns(5); if (ctx->features) { ImGui::Text("OA available: %s", ctx->features->features->has_i915_oa ? "true" : "false"); ImGui::Text("OA CPU timestamps available: %s", ctx->features->features->has_i915_oa_cpu_timestamps ? "true" : "false"); ImGui::Text("OA GPU timestamps available: %s", ctx->features->features->has_i915_oa_gpu_timestamps ? "true" : "false"); ImGui::Text("Server PID: %u", ctx->features->features->server_pid); ImGui::Text("Fake mode: %s", ctx->features->features->fake_mode ? "true" : "false"); } ImGui::NextColumn(); ImGui::Text("Available metrics: "); if (ctx->features) { ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth()); for (int u = 0; u < ctx->features->features->n_supported_oa_uuids; u++) { char input[100]; snprintf(input, sizeof(input), "%s", ctx->features->features->supported_oa_uuids[u]); ImGui::PushID(ctx->features->features->supported_oa_uuids[u]); ImGui::InputText("", input, sizeof(input), ImGuiInputTextFlags_ReadOnly); ImGui::PopID(); } } ImGui::PopItemWidth(); ImGui::NextColumn(); if (ctx->last_header) { const uint32_t *last_report = (const uint32_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, ctx->last_header, GPUTOP_I915_PERF_FIELD_OA_REPORT); for (uint32_t i = 0; i < 64; i++) ImGui::Text("%u\t: 0x%08x", i, last_report[i]); ImGui::Text("last_oa_timestamp: %" PRIx64, ctx->last_oa_timestamp); } // ImGui::NextColumn(); // if (ctx->n_timelines > 0) { // struct gputop_accumulated_samples *first = // list_first_entry(&ctx->timelines, struct gputop_accumulated_samples, link); // struct gputop_accumulated_samples *last = // list_last_entry(&ctx->timelines, struct gputop_accumulated_samples, link); // uint64_t total_time = last->timestamp_start - first->timestamp_end; // list_for_each_entry_safe(struct gputop_hw_context, context, // &ctx->hw_contexts, link) { // ImGui::Text("hw_id %" PRIx64 " : %.2f", context->hw_id, // 100.0f * ((double)context->time_spent / total_time)); // } // } ImGui::NextColumn(); ImGui::Text("HW Contexts"); // struct gputop_hw_context *hovered_context = NULL; list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { if (ImGui::TreeNode(context, "hw_id=%u/0x%x name=%s row=%i", context->hw_id, context->hw_id, context->name, context->timeline_row)) { ImGui::TreePop(); } // if (ImGui::IsItemHovered()) hovered_context = context; } ImGui::NextColumn(); ImGui::Text("Process infos"); list_for_each_entry(struct gputop_process_info, process_info, &ctx->process_infos, link) { ImGui::Text("pid=%u comm=%s", process_info->pid, process_info->cmd); } #if 0 ImGui::NextColumn(); struct { uint64_t start; uint64_t end; } hovered_window = { 0ULL, 0ULL }; list_for_each_entry(struct gputop_accumulated_samples, samples, &ctx->timelines, link) { const uint64_t *cpu_ts0 = (const uint64_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, samples->start_report.header, GPUTOP_I915_PERF_FIELD_CPU_TIMESTAMP); const uint64_t *cpu_ts1 = (const uint64_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, samples->end_report.header, GPUTOP_I915_PERF_FIELD_CPU_TIMESTAMP); char cpu_time_length[20]; gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, cpu_ts0 ? (*cpu_ts1 - *cpu_ts0) : 0UL, cpu_time_length, sizeof(cpu_time_length)); char gpu_time_length[20]; gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, samples->accumulator.last_timestamp - samples->accumulator.first_timestamp, gpu_time_length, sizeof(gpu_time_length)); const uint8_t *report0 = (const uint8_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, samples->start_report.header, GPUTOP_I915_PERF_FIELD_OA_REPORT); const uint8_t *report1 = (const uint8_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, samples->end_report.header, GPUTOP_I915_PERF_FIELD_OA_REPORT); if (ImGui::TreeNode(samples, "%s oa_ts=%" PRIx64 "-%" PRIx64 " scaled_ts=%" PRIx64 "-%" PRIx64 "(%" PRIx64 ") time=%s/%s", samples->context->name, gputop_cc_oa_report_get_timestamp(report0), gputop_cc_oa_report_get_timestamp(report1), samples->timestamp_start, samples->timestamp_end, gputop_timebase_scale_ns(&ctx->devinfo, gputop_cc_oa_report_get_timestamp(report1) - gputop_cc_oa_report_get_timestamp(report0)), cpu_time_length, gpu_time_length)) { display_accumulated_reports(ctx, samples, false); ImGui::TreePop(); } if (ImGui::IsItemHovered() && cpu_ts0) { hovered_window.start = *cpu_ts0; hovered_window.end = *cpu_ts1; } } ImGui::NextColumn(); const bool has_filter = (hovered_window.start != hovered_window.end) || hovered_context; list_for_each_entry(struct gputop_i915_perf_chunk, chunk, &ctx->i915_perf_chunks, link) { for (const struct drm_i915_perf_record_header *header = (const struct drm_i915_perf_record_header *) chunk->data; (const uint8_t *) header < (chunk->data + chunk->length); header = (const struct drm_i915_perf_record_header *) (((const uint8_t *)header) + header->size)) { switch (header->type) { case DRM_I915_PERF_RECORD_OA_BUFFER_LOST: ImGui::Text("OA buffer lost"); break; case DRM_I915_PERF_RECORD_OA_REPORT_LOST: ImGui::Text("OA report lost"); break; case DRM_I915_PERF_RECORD_SAMPLE: { const uint64_t *cpu_timestamp = (const uint64_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, header, GPUTOP_I915_PERF_FIELD_CPU_TIMESTAMP); const uint64_t *gpu_timestamp = (const uint64_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, header, GPUTOP_I915_PERF_FIELD_GPU_TIMESTAMP); const uint8_t *report = (const uint8_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, header, GPUTOP_I915_PERF_FIELD_OA_REPORT); const bool visible = !has_filter || (cpu_timestamp && *cpu_timestamp >= hovered_window.start && *cpu_timestamp <= hovered_window.end) || (hovered_context && gputop_cc_oa_report_get_ctx_id(&ctx->devinfo, report) == hovered_context->hw_id); if (visible && ImGui::TreeNodeEx(report, has_filter ? (ImGuiTreeNodeFlags_Selected | ImGuiTreeNodeFlags_DefaultOpen) : 0, "rcs=%08" PRIx64 " rcs64=%016" PRIx64 " cpu=%" PRIx64, gputop_cc_oa_report_get_timestamp(report), gpu_timestamp ? *gpu_timestamp : 0UL, cpu_timestamp ? *cpu_timestamp : 0UL)) { /* Display report fields */ ImGui::Text("hw_id=0x%x reason=%s", gputop_cc_oa_report_get_ctx_id(&ctx->devinfo, report), gputop_cc_oa_report_get_reason(&ctx->devinfo, report)); ImGui::TreePop(); } break; } default: ImGui::Text("i915 perf: Spurious header type = %d", header->type); break; } } } #endif } static void show_report_window(void) { struct window *window = &context.report_window; if (window->opened) { window->opened = false; return; } snprintf(window->name, sizeof(window->name), "Last perf report##%p", window); window->size = ImVec2(400, 400); window->display = display_report_window; window->destroy = hide_window; window->opened = true; list_add(&window->link, &context.windows); } /**/ static uint64_t get_end_timeline_ts(struct gputop_client_context *ctx, bool for_i915_perf) { struct gputop_accumulated_samples *oa_end = list_empty(&ctx->timelines) ? NULL : list_last_entry(&ctx->timelines, struct gputop_accumulated_samples, link); struct gputop_perf_tracepoint_data *tp_end = list_empty(&ctx->perf_tracepoints_data) ? NULL : list_last_entry(&ctx->perf_tracepoints_data, struct gputop_perf_tracepoint_data, link); if (for_i915_perf && !ctx->i915_perf_config.cpu_timestamps) tp_end = NULL; return MAX2(oa_end ? oa_end->timestamp_end : 0, tp_end ? tp_end->data.time : 0); } static void get_timeline_bounds(struct timeline_window *window, struct gputop_client_context *ctx, bool for_i915_perf, uint64_t *start, uint64_t *end, uint64_t zoom_start, uint64_t zoom_length) { uint64_t merged_end_ts = get_end_timeline_ts(ctx, for_i915_perf); const uint64_t max_length = ctx->oa_visible_timeline_s * 1000000000ULL; uint64_t start_ts = merged_end_ts - MIN2(max_length, merged_end_ts) + zoom_start; uint64_t end_ts = zoom_length == 0 ? merged_end_ts : start_ts + zoom_length; *start = start_ts; *end = end_ts; } static void tracepoint_print_prev_next(struct gputop_client_context *ctx, char *buf, size_t len, struct gputop_perf_tracepoint_data *data) { struct gputop_perf_tracepoint *tp = data->tp; struct gputop_perf_tracepoint_data *other; char pretty_value[100]; other = (data->tp_link.prev == &tp->data) ? NULL : LIST_ENTRY(struct gputop_perf_tracepoint_data, data->tp_link.prev, tp_link); if (other) { gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, data->data.time - other->data.time, pretty_value, sizeof(pretty_value)); int l = snprintf(buf, len, "\nprev @ %s", pretty_value); buf += l; len -= l; } other = (data->tp_link.next == &tp->data) ? NULL : LIST_ENTRY(struct gputop_perf_tracepoint_data, data->tp_link.next, tp_link); if (other) { gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, other->data.time - data->data.time, pretty_value, sizeof(pretty_value)); int l = snprintf(buf, len, "\nnext @ %s", pretty_value); buf += l; len -= l; } } static bool timeline_select_context(struct timeline_window *window, struct gputop_client_context *ctx, struct gputop_hw_context **out_context) { bool selected = false; if (ImGui::Button("Move to context")) ImGui::OpenPopup("Move to context"); if (ImGui::BeginPopup("Move to context")) { list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { if (ImGui::Selectable(context->name)) { *out_context = context; selected = true; } } ImGui::EndPopup(); } return selected; } static void timeline_focus_on_first_sample(struct timeline_window *window, struct gputop_client_context *ctx, struct gputop_hw_context *context) { uint64_t start_ts, end_ts; get_timeline_bounds(window, ctx, true, &start_ts, &end_ts, window->zoom_start, window->zoom_length); list_for_each_entry(struct gputop_accumulated_samples, samples, &ctx->timelines, link) { if (samples->timestamp_end < start_ts) continue; if (samples->timestamp_start > end_ts) break; if (samples->context != context) continue; const uint64_t max_length = ctx->oa_visible_timeline_s * 1000000000ULL; uint64_t total_end_ts = get_end_timeline_ts(ctx, true); uint64_t ts_length = samples->timestamp_end - samples->timestamp_start; ts_length *= 2; window->zoom_start = (samples->timestamp_start - ts_length / 4) - (total_end_ts - max_length); window->zoom_length = ts_length; break; } } static bool timeline_select_gt_timestamp(struct timeline_window *window, struct gputop_client_context *ctx) { bool modified = false; if (ImGui::Button("Move to timestamp")) ImGui::OpenPopup("Move to timestamp"); if (ImGui::BeginPopup("Move to timestamp")) { modified = ImGui::InputText("Timestamp (hexa)", window->gt_timestamp_highlight_str, sizeof(window->gt_timestamp_highlight_str), ImGuiInputTextFlags_EnterReturnsTrue); if (modified) { window->gt_timestamp_highlight = strtol(window->gt_timestamp_highlight_str, NULL, 16); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } return modified; } static void timeline_focus_on_gt_timestamp(struct timeline_window *window, struct gputop_client_context *ctx, uint64_t gt_timestamp) { list_for_each_entry(struct gputop_accumulated_samples, samples, &ctx->timelines, link) { if (gputop_i915_perf_record_timestamp(&ctx->i915_perf_config, samples->end_report.header) < gt_timestamp) continue; if (gputop_i915_perf_record_timestamp(&ctx->i915_perf_config, samples->start_report.header) > gt_timestamp) break; const uint64_t max_length = ctx->oa_visible_timeline_s * 1000000000ULL; uint64_t total_end_ts = get_end_timeline_ts(ctx, true); uint64_t ts_length = samples->timestamp_end - samples->timestamp_start; ts_length *= 2; window->zoom_start = (samples->timestamp_start - ts_length / 4) - (total_end_ts - max_length); window->zoom_length = ts_length; break; } } static void timeline_highlight_timestamps(struct timeline_window *window, struct gputop_client_context *ctx) { if (ImGui::Button("Highlight timestamps")) ImGui::OpenPopup("Highlight timestamps"); if (ImGui::BeginPopup("Highlight timestamps")) { if (ImGui::InputTextMultiline("Timestamps", window->gt_timestamps_list, sizeof(window->gt_timestamps_list))) { char *str = window->gt_timestamps_list, *str_end = window->gt_timestamps_list + strlen(window->gt_timestamps_list); window->n_gt_timestamps_display = 0; while (str < str_end && window->n_gt_timestamps_display < ARRAY_SIZE(window->gt_timestamps_display)) { char *next_str = NULL; uint32_t gt_timestamp = strtol(str, &next_str, 16); window->gt_timestamps_display[window->n_gt_timestamps_display++] = gputop_client_context_convert_gt_timestamp(ctx, gt_timestamp); if (!next_str || next_str == str) break; str = next_str; } } for (int i = 0; i < window->n_gt_timestamps_display; i++) { ImGui::Text("%i: %lu\n", i, window->gt_timestamps_display[i]); } ImGui::EndPopup(); } } static void update_timeline_report_range(struct timeline_window *window, struct gputop_client_context *ctx, const struct drm_i915_perf_record_header *start, const struct drm_i915_perf_record_header *end) { if (!start) { snprintf(window->gt_timestamp_range, sizeof(window->gt_timestamp_range), "no selection"); return; } snprintf(window->gt_timestamp_range, sizeof(window->gt_timestamp_range), "ts: 0x%x(%s) - 0x%x(%s)", gputop_i915_perf_record_timestamp(&ctx->i915_perf_config, start), gputop_i915_perf_record_reason(&ctx->i915_perf_config, &ctx->devinfo, start), gputop_i915_perf_record_timestamp(&ctx->i915_perf_config, end), gputop_i915_perf_record_reason(&ctx->i915_perf_config, &ctx->devinfo, end)); } static void search_timeline_reports_for_timestamp(struct timeline_window *window, struct gputop_client_context *ctx) { if (strlen(window->timestamp_search) < 1) { window->searched_timestamp = -1; window->hovered_report = -1; return; } const struct drm_i915_perf_record_header *last = NULL; struct gputop_record_iterator iter; uint32_t ts = strtol(window->timestamp_search, NULL, 16); int report = 0; gputop_record_iterator_init(&iter, &window->selected_sample); while (gputop_record_iterator_next(&iter)) { if (iter.header->type != DRM_I915_PERF_RECORD_SAMPLE) continue; uint32_t report_ts = gputop_i915_perf_record_timestamp(&ctx->i915_perf_config, iter.header); if (ts < report_ts) { window->searched_timestamp = report_ts; window->hovered_report = report; update_timeline_report_range(window, ctx, last, iter.header); return; } last = iter.header; report++; } window->searched_timestamp = -1; window->hovered_report = -1; } static void update_timeline_selected_reports(struct timeline_window *window, struct gputop_client_context *ctx, struct gputop_accumulated_samples *sample) { if (window->selected_sample.start_report.header == sample->start_report.header) return; memcpy(&window->selected_sample, sample, sizeof(window->selected_sample)); memcpy(&window->selected_context, sample->context, sizeof(window->selected_context)); struct gputop_record_iterator iter; int n_reports = 0; gputop_record_iterator_init(&iter, sample); while (gputop_record_iterator_next(&iter)) { if (iter.header->type == DRM_I915_PERF_RECORD_SAMPLE) n_reports++; } assert(n_reports > 1); int n_accumulated_reports = n_reports - 1; int n_counters = ctx->metric_set->n_counters; free(window->accumulated_values); window->accumulated_values = (float *) calloc(n_accumulated_reports * n_counters, sizeof(float)); window->n_accumulated_reports = n_accumulated_reports; window->hovered_report = -1; const uint8_t *last_report = NULL; int i = 0; gputop_record_iterator_init(&iter, sample); while (gputop_record_iterator_next(&iter)) { if (iter.header->type != DRM_I915_PERF_RECORD_SAMPLE) continue; const uint8_t *report = (const uint8_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, iter.header, GPUTOP_I915_PERF_FIELD_OA_REPORT); if (!last_report) { last_report = report; continue; } struct gputop_cc_oa_accumulator accumulator; gputop_cc_oa_accumulator_init(&accumulator, &ctx->devinfo, ctx->metric_set, 0, NULL); gputop_cc_oa_accumulate_reports(&accumulator, last_report, report); for (int c = 0; c < n_counters; c++) { struct gputop_metric_set_counter *counter = &ctx->metric_set->counters[c]; float *value = &window->accumulated_values[c * n_accumulated_reports + i]; switch (counter->data_type) { case GPUTOP_PERFQUERY_COUNTER_DATA_UINT64: case GPUTOP_PERFQUERY_COUNTER_DATA_UINT32: case GPUTOP_PERFQUERY_COUNTER_DATA_BOOL32: *value = counter->oa_counter_read_uint64(&ctx->devinfo, ctx->metric_set, accumulator.deltas); break; case GPUTOP_PERFQUERY_COUNTER_DATA_DOUBLE: case GPUTOP_PERFQUERY_COUNTER_DATA_FLOAT: *value = counter->oa_counter_read_float(&ctx->devinfo, ctx->metric_set, accumulator.deltas); break; } } i++; last_report = report; } search_timeline_reports_for_timestamp(window, ctx); } static void display_timeline_window(struct window *win) { struct gputop_client_context *ctx = &context.ctx; struct timeline_window *window = (struct timeline_window *) win; const uint64_t max_length = ctx->oa_visible_timeline_s * 1000000000ULL; if (StartStopSamplingButton(ctx)) { toggle_start_stop_sampling(ctx); } ImGui::Text("RCS/Render timeline:"); ImGui::SameLine(); { char time[20]; gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, window->zoom_length == 0 ? max_length : window->zoom_length, time, sizeof(time)); ImGui::Text("time interval : %s", time); } if (ImGui::Button("Reset zoom##i915")) { window->zoom_start = 0; window->zoom_length = max_length; } ImGui::SameLine(); if (ImGui::Button("Zoom out##i915")) { uint64_t half_zoom = window->zoom_length / 2; window->zoom_start = window->zoom_start < half_zoom ? 0ULL : (window->zoom_start - half_zoom); window->zoom_length = MIN2(2 * window->zoom_length, max_length); } ImGui::SameLine(); if (ImGui::Button("Zoom in##i915")) { window->zoom_start += window->zoom_length / 4; window->zoom_length /= 2; } ImGui::SameLine(); struct gputop_hw_context *selected_context = NULL; if (timeline_select_context(window, ctx, &selected_context)) { timeline_focus_on_first_sample(window, ctx, selected_context); } ImGui::SameLine(); if (timeline_select_gt_timestamp(window, ctx)) { timeline_focus_on_gt_timestamp(window, ctx, window->gt_timestamp_highlight); } ImGui::SameLine(); timeline_highlight_timestamps(window, ctx); if (ImGui::Button("Counters")) { toggle_show_window(&window->counters_window); } ImGui::SameLine(); if (ImGui::Button("Events")) { toggle_show_window(&window->events_window); } ImGui::SameLine(); if (ImGui::Button("RCS usage")) { toggle_show_window(&window->usage_window); } ImGui::SameLine(); if (ImGui::Button("OA reports")) { toggle_show_window(&window->reports_window); } uint64_t start_ts, end_ts; get_timeline_bounds(window, ctx, true, &start_ts, &end_ts, window->zoom_start, window->zoom_length); ImVec2 new_zoom; static const char *units[] = { "ns", "us", "ms", "s" }; char **row_names = ensure_timeline_names(_mesa_hash_table_num_entries(ctx->hw_contexts_table)); uint32_t n_rows = 0; list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) row_names[n_rows++] = context->name; int n_tps = list_length(&ctx->perf_tracepoints); Gputop::BeginTimeline("i915-perf-timeline", n_rows, n_tps, end_ts - start_ts, ImVec2(ImGui::GetContentRegionAvailWidth(), 300.0f)); list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { context->visible_time = end_ts - start_ts; context->visible_time_spent = 0UL; } uint32_t n_entries = 0; list_for_each_entry(struct gputop_accumulated_samples, samples, &ctx->timelines, link) { if (samples->timestamp_end < start_ts) continue; if (samples->timestamp_start > end_ts) break; if (samples->context) { samples->context->visible_time_spent += MIN2(samples->timestamp_end, end_ts) - MAX2(samples->timestamp_start, start_ts); } n_entries++; assert(samples->context->timeline_row < n_rows); if (Gputop::TimelineItem(samples->context->timeline_row, MAX2(samples->timestamp_start, start_ts) - start_ts, samples->timestamp_end - start_ts, false)) { update_timeline_selected_reports(window, ctx, samples); char pretty_time[20]; gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, samples->timestamp_end - samples->timestamp_start, pretty_time, sizeof(pretty_time)); ImGui::SetTooltip("%s : %s", samples->context->name, pretty_time); } } for (int i = 0; i < window->n_gt_timestamps_display; i++) { if (window->gt_timestamps_display[i] < start_ts || window->gt_timestamps_display[i] > end_ts) { continue; } Gputop::TimelineCustomEvent(window->gt_timestamps_display[i] - start_ts, Gputop::GetColor(GputopCol_TimelineHighlightedTs)); } const bool separate_timeline = !ctx->i915_perf_config.cpu_timestamps && list_length(&ctx->perf_tracepoints) > 0; if (separate_timeline) { int64_t zoom_start; uint64_t zoom_end; if (Gputop::EndTimeline(units, ARRAY_SIZE(units), (const char **) row_names, &zoom_start, &zoom_end)) { window->zoom_start = MAX2(window->zoom_length == 0 ? zoom_start : (window->zoom_start + zoom_start), 0); window->zoom_length = MIN2(zoom_end - zoom_start, max_length); } ImGui::Text("Tracepoint timeline:"); ImGui::SameLine(); if (ImGui::Button("Reset zoom##tp")) { window->zoom_tp_start = 0; window->zoom_tp_length = max_length; } ImGui::SameLine(); if (ImGui::Button("Zoom out##tp")) { uint64_t half_zoom = window->zoom_tp_length / 2; window->zoom_tp_start = window->zoom_tp_start < half_zoom ? 0ULL : (window->zoom_tp_start - half_zoom); window->zoom_tp_length = MIN2(2 * window->zoom_tp_length, max_length); } ImGui::SameLine(); if (ImGui::Button("Zoom in##tp")) { window->zoom_tp_start += window->zoom_tp_length / 4; window->zoom_tp_length /= 2; } ImGui::SameLine(); { char time[20]; gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, window->zoom_tp_length == 0 ? max_length : window->zoom_tp_length, time, sizeof(time)); ImGui::Text("time interval : %s", time); } get_timeline_bounds(window, ctx, false, &start_ts, &end_ts, window->zoom_tp_start, window->zoom_tp_length); Gputop::BeginTimeline("tp-timeline", n_rows, n_tps, end_ts - start_ts, ImVec2(ImGui::GetContentRegionAvailWidth(), 300.0f)); } list_for_each_entry(struct gputop_perf_tracepoint_data, data, &ctx->perf_tracepoints_data, link) { if (data->data.time < start_ts) continue; if (data->data.time > end_ts) break; if (Gputop::TimelineEvent(data->tp->idx, MAX2(data->data.time, start_ts) - start_ts, data->data.time == window->tracepoint_selected_ts)) { struct gputop_perf_tracepoint *tp = data->tp; char point_desc[200]; gputop_client_context_print_tracepoint_data(ctx, point_desc, sizeof(point_desc), data, true); if (!strcmp(tp->name, "drm/drm_vblank_event")) { char prev_next[100]; tracepoint_print_prev_next(ctx, prev_next, sizeof(prev_next), data); ImGui::SetTooltip("%s\n%s", point_desc, prev_next); } else { ImGui::SetTooltip("%s", point_desc); } memcpy(&window->tracepoint, data->tp, sizeof(window->tracepoint)); } } int64_t zoom_start; uint64_t zoom_end; if (Gputop::EndTimeline(units, ARRAY_SIZE(units), (const char **) row_names, &zoom_start, &zoom_end)) { uint64_t *p_z_start = separate_timeline ? &window->zoom_tp_start : &window->zoom_start, *p_z_length = separate_timeline ? &window->zoom_tp_length : &window->zoom_length; *p_z_start = MAX2(*p_z_length == 0 ? *p_z_start : (*p_z_start + zoom_start), 0); *p_z_length = MIN2(zoom_end - zoom_start, max_length); } } static void display_timeline_counters(struct window *win) { struct timeline_window *window = (struct timeline_window *) container_of(win, window, counters_window); struct gputop_client_context *ctx = &context.ctx; int n_contexts = _mesa_hash_table_num_entries(ctx->hw_contexts_table); ImGui::ColorButton("##selected_context", Gputop::GetHueColor(window->selected_context.timeline_row, n_contexts), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoTooltip); ImGui::SameLine(); ImGui::Text("%s", window->selected_context.name); ImGui::SameLine(); static ImGuiTextFilter filter; filter.Draw(); ImGui::BeginChild("##counters"); display_i915_perf_counters(ctx, &filter, &window->selected_sample, false); ImGui::EndChild(); } static void display_timeline_events(struct window *win) { struct timeline_window *window = (struct timeline_window *) container_of(win, window, events_window); struct gputop_client_context *ctx = &context.ctx; uint64_t start_ts, end_ts; if (ctx->i915_perf_config.cpu_timestamps) { get_timeline_bounds(window, ctx, false, &start_ts, &end_ts, window->zoom_start, window->zoom_length); } else { get_timeline_bounds(window, ctx, false, &start_ts, &end_ts, window->zoom_tp_start, window->zoom_tp_length); } int n_items = 0, n_tps = list_length(&ctx->perf_tracepoints); window->tracepoint_selected_ts = 0ULL; list_for_each_entry(struct gputop_perf_tracepoint_data, data, &ctx->perf_tracepoints_data, link) { if (data->data.time < start_ts) continue; if (data->data.time > end_ts || n_items > 100) break; char desc[20]; snprintf(desc, sizeof(desc), "##%p", data); ImGui::ColorButton(desc, Gputop::GetHueColor(data->tp->idx, n_tps), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoTooltip); ImGui::SameLine(); char point_desc[200]; gputop_client_context_print_tracepoint_data(ctx, point_desc, sizeof(point_desc), data, true); ImGui::Selectable(point_desc); if (ImGui::IsItemHovered()) window->tracepoint_selected_ts = data->data.time; n_items++; } } static void search_timeline_reports_for_column(struct timeline_window *window, struct gputop_client_context *ctx, int column) { if (window->searched_timestamp != -1) return; const struct drm_i915_perf_record_header *last = NULL; struct gputop_record_iterator iter; int c = 0; gputop_record_iterator_init(&iter, &window->selected_sample); while (c <= column && gputop_record_iterator_next(&iter)) { if (iter.header->type != DRM_I915_PERF_RECORD_SAMPLE) continue; last = iter.header; c++; } gputop_record_iterator_next(&iter); window->hovered_report = column; update_timeline_report_range(window, ctx, last, iter.header); } static void display_timeline_reports(struct window *win) { struct timeline_window *window = (struct timeline_window *) container_of(win, window, reports_window); struct gputop_client_context *ctx = &context.ctx; if (ctx->is_sampling || !ctx->metric_set) return; int n_contexts = _mesa_hash_table_num_entries(ctx->hw_contexts_table); ImGui::ColorButton("##selected_context", Gputop::GetHueColor(window->selected_context.timeline_row, n_contexts), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoTooltip); ImGui::SameLine(); char pretty_time[20]; gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, window->selected_sample.timestamp_end - window->selected_sample.timestamp_start, pretty_time, sizeof(pretty_time)); ImGui::Text("%s: %u reports, %s, %s", window->selected_context.name, window->n_accumulated_reports, pretty_time, window->gt_timestamp_range); ImGui::Text("Timestamp search:"); if (ImGui::InputText("(hexadecimal)", window->timestamp_search, sizeof(window->timestamp_search))) search_timeline_reports_for_timestamp(window, ctx); ImGui::SameLine(); if (ImGui::Button("Show OA report")) { toggle_show_window(&window->report_window); } static ImGuiTextFilter filter; ImGui::Text("Filter counters:"); ImGui::SameLine(); filter.Draw(); if (window->n_accumulated_reports < 1) return; ImGui::BeginChild("##reports"); int32_t new_hovered_column = -1; for (int c = 0; c < ctx->metric_set->n_counters; c++) { struct gputop_metric_set_counter *counter = &ctx->metric_set->counters[c]; if (!filter.PassFilter(counter->name)) continue; float *values = &window->accumulated_values[c * window->n_accumulated_reports]; ImGui::PushID(counter); int hovered = Gputop::PlotHistogram("", values, window->n_accumulated_reports, 0, window->hovered_report); ImGui::PopID(); ImGui::SameLine(); if (hovered >= 0) { char tooltip_text[80]; pretty_print_counter_value(counter, values[hovered], tooltip_text, sizeof(tooltip_text)); ImGui::SetTooltip("%s", tooltip_text); new_hovered_column = hovered; } if (window->hovered_report >= 0) { char hovered_text[80]; pretty_print_counter_value(counter, values[window->hovered_report], hovered_text, sizeof(hovered_text)); ImGui::Text("%s - %s", counter->name, hovered_text); } else { ImGui::Text("%s", counter->name); } if (ImGui::IsItemHovered()) { ImGui::SetTooltip("%s", counter->desc); } } if (window->hovered_report != new_hovered_column) search_timeline_reports_for_column(window, ctx, new_hovered_column); ImGui::EndChild(); } static void display_timeline_report(struct window *win) { struct timeline_window *window = (struct timeline_window *) container_of(win, window, report_window); struct gputop_client_context *ctx = &context.ctx; if (window->hovered_report < 0) return; struct gputop_record_iterator iter; int c = 0; gputop_record_iterator_init(&iter, &window->selected_sample); while (c <= window->hovered_report && gputop_record_iterator_next(&iter)) { if (iter.header->type != DRM_I915_PERF_RECORD_SAMPLE) continue; c++; } const uint32_t *report = (const uint32_t *) gputop_i915_perf_record_field(&ctx->i915_perf_config, iter.header, GPUTOP_I915_PERF_FIELD_OA_REPORT); for (int i = 0; i < 64; i++) ImGui::Text("0x%x", report[i]); } static void display_timeline_usage(struct window *win) { struct timeline_window *window = (struct timeline_window *) container_of(win, window, usage_window); struct gputop_client_context *ctx = &context.ctx; char pretty_time[80]; gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, window->zoom_length, pretty_time, sizeof(pretty_time)); ImGui::Text("Total time: %s", pretty_time); if (window->zoom_length < 1) return; uint64_t contexts_time = 0ULL, visible_time = window->zoom_length; float pie_ray = MIN2(ImGui::GetContentRegionAvail().y, ImGui::GetWindowContentRegionWidth() / 2); int n_clients = list_length(&ctx->hw_contexts) + 1; Gputop::BeginPieChart(n_clients, ImVec2(pie_ray, pie_ray)); ImGui::SameLine(); list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { if (context->visible_time == 0) /* Data not computed yet. */ continue; visible_time = context->visible_time; double percent = (double) context->visible_time_spent / context->visible_time; if (Gputop::PieChartItem(percent)) { gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, context->visible_time_spent, pretty_time, sizeof(pretty_time)); ImGui::SetTooltip("%s: %s", context->name, pretty_time); } contexts_time += context->visible_time_spent; } uint64_t idle_time = visible_time - contexts_time; double idle_percent = (double) idle_time / visible_time; if (Gputop::PieChartItem(idle_percent)) { gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, idle_time, pretty_time, sizeof(pretty_time)); ImGui::SetTooltip("Idle: %s", pretty_time); } Gputop::EndPieChart(); ImGui::BeginChild("#contextlist"); contexts_time = 0ULL; list_for_each_entry(struct gputop_hw_context, context, &ctx->hw_contexts, link) { ImGui::ProgressBar((double) context->visible_time_spent / context->visible_time, ImVec2(ImGui::GetWindowContentRegionWidth() / 2.0f, 0)); ImGui::SameLine(); gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, context->visible_time_spent, pretty_time, sizeof(pretty_time)); ImGui::Text("%s: %s", context->name, pretty_time); } ImGui::ProgressBar(idle_percent, ImVec2(ImGui::GetWindowContentRegionWidth() / 2.0f, 0)); ImGui::SameLine(); gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, idle_time, pretty_time, sizeof(pretty_time)); ImGui::Text("Idle: %s", pretty_time); ImGui::EndChild(); } static void hide_timeline_window(struct window *win) { struct timeline_window *window = (struct timeline_window *) win; window->reports_window.opened = false; window->usage_window.opened = false; } static void show_timeline_window(void) { struct timeline_window *window = &context.timeline_window; if (window->base.opened) { window->base.opened = false; window->reports_window.opened = false; return; } snprintf(window->base.name, sizeof(window->base.name), "i915 perf timeline##%p", window); window->base.size = ImVec2(800, 400); window->base.display = display_timeline_window; window->base.destroy = hide_timeline_window; window->base.opened = true; snprintf(window->counters_window.name, sizeof(window->counters_window.name), "i915 perf timeline counters##%p", &window->counters_window); window->counters_window.size = ImVec2(400, 400); window->counters_window.display = display_timeline_counters; window->counters_window.destroy = hide_window; window->counters_window.opened = false; snprintf(window->events_window.name, sizeof(window->events_window.name), "i915 perf timeline events##%p", &window->events_window); window->events_window.size = ImVec2(400, 400); window->events_window.display = display_timeline_events; window->events_window.destroy = hide_window; window->events_window.opened = false; snprintf(window->reports_window.name, sizeof(window->reports_window.name), "i915 perf timeline reports##%p", &window->reports_window); window->reports_window.size = ImVec2(400, 400); window->reports_window.display = display_timeline_reports; window->reports_window.destroy = hide_window; window->reports_window.opened = false; snprintf(window->report_window.name, sizeof(window->report_window.name), "i915 perf report view##%p", &window->report_window); window->report_window.size = ImVec2(400, 400); window->report_window.display = display_timeline_report; window->report_window.destroy = hide_window; window->report_window.opened = false; snprintf(window->usage_window.name, sizeof(window->usage_window.name), "i915 perf timeline usage##%p", &window->usage_window); window->usage_window.size = ImVec2(500, 300); window->usage_window.display = display_timeline_usage; window->usage_window.destroy = hide_window; window->usage_window.opened = false; window->searched_timestamp = -1; window->zoom_start = window->zoom_tp_start = 0; struct gputop_client_context *ctx = &context.ctx; window->zoom_length = window->zoom_tp_length = ctx->oa_visible_timeline_s * 1000000000ULL; list_add(&window->base.link, &context.windows); } /**/ static void display_tracepoints_window(struct window *win) { struct gputop_client_context *ctx = &context.ctx; ImGui::Columns(3); ImGui::BeginChild("##column1"); ImGui::Text("Available tracepoints"); ImGui::Separator(); static ImGuiTextFilter filter; filter.Draw(); ImGui::BeginChild("##tracepoints"); if (ctx->features) { for (unsigned i = 0; i < ctx->features->features->n_tracepoints; i++) { if (filter.PassFilter(ctx->features->features->tracepoints[i]) && ImGui::Selectable(ctx->features->features->tracepoints[i])) gputop_client_context_add_tracepoint(ctx, ctx->features->features->tracepoints[i]); } } ImGui::EndChild(); ImGui::EndChild(); ImGui::NextColumn(); ImGui::BeginChild("##column2"); ImGui::Text("Tracepoint format"); ImGui::Separator(); if (ctx->tracepoint_info) { ImGui::Text("event_id=%u", ctx->tracepoint_info->tracepoint_info->event_id); ImGui::InputTextMultiline("##format", ctx->tracepoint_info->tracepoint_info->sample_format, strlen(ctx->tracepoint_info->tracepoint_info->sample_format), ImGui::GetContentRegionAvail(), ImGuiInputTextFlags_ReadOnly); } ImGui::EndChild(); ImGui::NextColumn(); ImGui::BeginChild("##column3"); ImGui::Text("Selected tracepoints"); ImGui::Separator(); list_for_each_entry_safe(struct gputop_perf_tracepoint, tp, &ctx->perf_tracepoints, link) { if (ImGui::Selectable(tp->name)) { gputop_client_context_remove_tracepoint(ctx, tp); } } ImGui::EndChild(); } static void show_tracepoints_window(void) { struct window *window = &context.tracepoints_window; if (window->opened) { window->opened = false; return; } snprintf(window->name, sizeof(window->name), "Tracepoints##%p", window); window->size = ImVec2(800, 300); window->display = display_tracepoints_window; window->destroy = hide_window; window->opened = true; list_add(&window->link, &context.windows); } /**/ static void display_events_window(struct window *win) { struct gputop_client_context *ctx = &context.ctx; ImGui::Text("Available events"); ImGui::Separator(); static ImGuiTextFilter filter; filter.Draw(); ImGui::BeginChild("##events"); if (ctx->features) { for (unsigned i = 0; i < ctx->features->features->n_events; i++) { if (filter.PassFilter(ctx->features->features->events[i]) && ImGui::Selectable(ctx->features->features->events[i])) { } } } ImGui::EndChild(); } static void show_events_window(void) { struct window *window = &context.tracepoints_window; if (window->opened) { window->opened = false; return; } snprintf(window->name, sizeof(window->name), "Events##%p", window); window->size = ImVec2(800, 300); window->display = display_events_window; window->destroy = hide_window; window->opened = true; list_add(&window->link, &context.windows); } /**/ static void display_log_window(struct window *win) { struct gputop_client_context *ctx = &context.ctx; if (ImGui::Button("Clear")) { gputop_client_context_clear_logs(ctx); clear_client_logs(); } ImGui::Columns(2); ImGui::Text("Server:"); ImGui::BeginChild(ImGui::GetID("##server")); for (int i = 0; i < ctx->n_messages; i++) { int idx = (ctx->start_message + i) % ARRAY_SIZE(ctx->messages); ImGui::Text("%s", ctx->messages[idx].msg); } ImGui::EndChild(); ImGui::NextColumn(); ImGui::Text("Client:"); ImGui::BeginChild(ImGui::GetID("##client")); for (int i = 0; i < context.n_messages; i++) { int idx = (context.start_message + i) % ARRAY_SIZE(ctx->messages); ImGui::Text("%s", context.messages[idx].msg); } ImGui::EndChild(); } static void show_log_window(void) { struct window *window = &context.log_window; if (window->opened) { window->opened = false; return; } snprintf(window->name, sizeof(window->name), "Server logs"); window->size = ImVec2(400, 200); window->display = display_log_window; window->opened = true; window->destroy = hide_window; list_add(&window->link, &context.windows); } /**/ static void display_style_editor_window(struct window *win) { ImGuiColorEditFlags cflags = (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoInputs); ImGui::ColorEdit3("background", (float *)&context.clear_color, cflags); Gputop::DisplayColorsProperties(); } static void show_style_editor_window(void) { struct window *window = &context.style_editor_window; if (window->opened) { window->opened = false; return; } snprintf(window->name, sizeof(window->name), "Style editor"); window->size = ImVec2(400, 200); window->display = display_style_editor_window; window->opened = true; window->destroy = hide_window; list_add(&window->link, &context.windows); } /**/ static void display_streams_window(struct window *win) { struct gputop_client_context *ctx = &context.ctx; ImGui::Columns(2); ImGui::Text("Streams:"); list_for_each_entry(struct gputop_stream, stream, &ctx->streams, link) { ImGui::Text("id=%i", stream->id); ImGui::SameLine(); ImGui::ProgressBar(stream->fill / 100.0); } ImGui::NextColumn(); list_for_each_entry(struct gputop_perf_tracepoint, tp, &ctx->perf_tracepoints, link) { ImGui::Text("tp=%s id=%i", tp->name, tp->event_id); } ImGui::Text("n_timelines=%i", ctx->n_timelines); ImGui::Text("n_graphs=%i", ctx->n_graphs); ImGui::Text("n_cpu_stats=%i", ctx->n_cpu_stats); list_for_each_entry(struct gputop_perf_tracepoint_data, data, &ctx->perf_tracepoints_data, link) { ImGui::Text("%s time=%" PRIx64, data->tp->name, data->data.time); } } static void show_streams_window(void) { struct window *window = &context.streams_window; if (window->opened) { window->opened = false; return; } snprintf(window->name, sizeof(window->name), "Streams"); window->size = ImVec2(400, 200); window->display = display_streams_window; window->opened = true; window->destroy = hide_window; list_add(&window->link, &context.windows); } /**/ static float * get_cpus_stats(struct gputop_client_context *ctx, int max_cpu_stats) { int n_cpus = ctx->features ? ctx->features->features->n_cpus : 1; float *values = ensure_plot_accumulator(n_cpus * max_cpu_stats); int i; for (i = 0; i < max_cpu_stats - ctx->n_cpu_stats; i++) { for (int cpu = 0; cpu < n_cpus; cpu++) values[n_cpus * i + cpu] = 0.0f; } struct gputop_cpu_stat *stat = list_first_entry(&ctx->cpu_stats, struct gputop_cpu_stat, link); for (; i < (max_cpu_stats - 1); i++) { struct gputop_cpu_stat *next = list_first_entry(&stat->link, struct gputop_cpu_stat, link); assert(&next->link != &ctx->cpu_stats); for (int cpu = 0; cpu < n_cpus; cpu++) { Gputop__CpuStats *cpu_stat0 = stat->stat->cpu_stats->cpus[cpu]; Gputop__CpuStats *cpu_stat1 = next->stat->cpu_stats->cpus[cpu]; uint32_t total = ((cpu_stat1->user - cpu_stat0->user) + (cpu_stat1->nice - cpu_stat0->nice) + (cpu_stat1->system - cpu_stat0->system) + (cpu_stat1->idle - cpu_stat0->idle) + (cpu_stat1->iowait - cpu_stat0->iowait) + (cpu_stat1->irq - cpu_stat0->irq) + (cpu_stat1->softirq - cpu_stat0->softirq) + (cpu_stat1->steal - cpu_stat0->steal) + (cpu_stat1->guest - cpu_stat0->guest) + (cpu_stat1->guest_nice - cpu_stat0->guest_nice)); if (total == 0) values[n_cpus * i + cpu] = 0.0f; else { values[n_cpus * i + cpu] = 100.0f - 100.f * (float) (cpu_stat1->idle - cpu_stat0->idle) / total; } } stat = next; } return values; } struct cpu_stat_getter { float *values; int n_cpus; }; static float get_cpu_stat_item(void *data, int line, int idx) { struct cpu_stat_getter *getter = (struct cpu_stat_getter *) data; return getter->values[idx * getter->n_cpus + line]; } static void display_cpu_stats(void) { struct gputop_client_context *ctx = &context.ctx; int n_cpus = ctx->features ? ctx->features->features->n_cpus : 1; int max_cpu_stats = (int) (ctx->cpu_stats_visible_timeline_s * 1000.0f) / ctx->cpu_stats_sampling_period_ms; struct cpu_stat_getter getter = { get_cpus_stats(ctx, max_cpu_stats), n_cpus }; char title[20]; snprintf(title, sizeof(title), "%i CPU(s)", n_cpus); Gputop::PlotMultilines("", &get_cpu_stat_item, &getter, n_cpus, max_cpu_stats - 1, 0, context.cpu_colors, title, 0.0f, 100.0f, ImVec2(ImGui::GetContentRegionAvailWidth(), 100.0f)); } static bool select_metric_set(struct gputop_client_context *ctx, const struct gputop_metric_set **out_metric_set) { bool selected = false; static ImGuiTextFilter filter; filter.Draw(); if (!ctx->features) return false; ImGui::BeginChild("##block"); for (unsigned u = 0; u < ctx->features->features->n_supported_oa_uuids; u++) { const struct gputop_metric_set *metric_set = gputop_client_context_uuid_to_metric_set(ctx, ctx->features->features->supported_oa_uuids[u]); if (!metric_set) continue; if (filter.PassFilter(metric_set->name) && ImGui::Selectable(metric_set->name)) { *out_metric_set = metric_set; selected = true; } } ImGui::EndChild(); return selected; } static bool select_metric_set_from_group_counter(struct gputop_counter_group *group, ImGuiTextFilter *filter, const struct gputop_metric_set **out_metric_set) { bool selected = false; ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Framed | (filter->IsActive() ? ImGuiTreeNodeFlags_DefaultOpen : 0); list_for_each_entry(struct gputop_counter_group, subgroup, &group->groups, link) { if (ImGui::TreeNodeEx(subgroup, flags, "%s", subgroup->name)) { if (select_metric_set_from_group_counter(subgroup, filter, out_metric_set)) { selected = true; } ImGui::TreePop(); } } list_for_each_entry(struct gputop_metric_set_counter, counter, &group->counters, link) { if (!filter->PassFilter(counter->name)) continue; char counter_name[120]; snprintf(counter_name, sizeof(counter_name), "%s (%s)", counter->name, counter->metric_set->name); if (ImGui::Selectable(counter_name)) { *out_metric_set = counter->metric_set; selected = true; } } return selected; } static bool select_metric_set_from_counter(struct gputop_client_context *ctx, const struct gputop_metric_set **out_metric_set) { static ImGuiTextFilter filter; filter.Draw(); if (!ctx->features) return false; ImGui::BeginChild("##block"); bool selected = select_metric_set_from_group_counter(ctx->gen_metrics->root_group, &filter, out_metric_set); ImGui::EndChild(); return selected; } static void maybe_restart_sampling(struct gputop_client_context *ctx) { if (ctx->is_sampling) { gputop_client_context_stop_sampling(ctx); gputop_client_context_start_sampling(ctx); } } static bool select_oa_exponent(struct gputop_client_context *ctx, uint64_t *ns) { bool open_popup = ImGui::Button("OA exponents"); if (open_popup) ImGui::OpenPopup("oa exponent picker"); ImGui::SetNextWindowSize(ImVec2(200, 400)); bool selected = false; if (ImGui::BeginPopup("oa exponent picker")) { if (ctx->connection) { for (uint32_t e = 1; e < 32; e++) { uint64_t duration_ns = gputop_oa_exponent_to_period_ns(&ctx->devinfo, e); char pretty_duration[200]; gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, duration_ns, pretty_duration, sizeof(pretty_duration)); if (ImGui::Selectable(pretty_duration)) { ImGui::CloseCurrentPopup(); *ns = duration_ns; selected = true; } } } ImGui::EndPopup(); } return selected; } static void display_main_window(struct window *win) { struct gputop_client_context *ctx = &context.ctx; char buf[80]; if (ImGui::Button("Style editor")) { show_style_editor_window(); } ImGui::SameLine(); int n_messages = context.n_messages + ctx->n_messages; if (n_messages > 0) snprintf(buf, sizeof(buf), "Logs (%i)", n_messages); else snprintf(buf, sizeof(buf), "Logs"); if (ImGui::Button(buf)) { show_log_window(); } ImGui::SameLine(); if (ImGui::Button("Report")) { show_report_window(); } ImGui::SameLine(); if (ImGui::Button("Streams")) { show_streams_window(); } if (ImGui::InputText("Address", context.host_address, sizeof(context.host_address), ImGuiInputTextFlags_EnterReturnsTrue)) { reconnect(); } if (ImGui::InputInt("Port", &context.host_port, 1, 100, ImGuiInputTextFlags_EnterReturnsTrue)) { reconnect(); } if (ImGui::Button("Connect")) { reconnect(); } ImGui::SameLine(); ImGui::Text("Status:"); ImGui::SameLine(); bool is_connected = (ctx->connection && gputop_connection_connected(ctx->connection)); ImColor color = is_connected ? ImColor(0.0f, 1.0f, 0.0f) : ImColor(0.9f, 0.0f, 0.0f); const char *connection_status = ctx->connection ? (is_connected ? "Connected" : "Connecting...") : (context.connection_error ? context.connection_error : "Not connected"); ImGui::TextColored(color, "%s", connection_status); /* CPU */ ImGui::Separator(); if (ctx->features) { ImGui::Text("CPU model: %s", ctx->features->features->cpu_model); ImGui::Text("Kernel release: %s", ctx->features->features->kernel_release); ImGui::Text("Kernel build: %s", ctx->features->features->kernel_build); } int vcpu = ctx->cpu_stats_sampling_period_ms; if (ImGui::InputInt("CPU sampling period (ms)", &vcpu)) { vcpu = CLAMP(vcpu, 1, 1000); if (vcpu != ctx->cpu_stats_sampling_period_ms) { gputop_client_context_update_cpu_stream(ctx, vcpu); } } ImGui::SliderFloat("CPU visible sampling (s)", &ctx->cpu_stats_visible_timeline_s, 0.1f, 15.0f); if (ImGui::Button("Select events")) { show_events_window(); } ImGui::SameLine(); snprintf(buf, sizeof(buf), "Select tracepoints (%i)", list_length(&ctx->perf_tracepoints)); if (ImGui::Button(buf)) { show_tracepoints_window(); } ImGui::SameLine(); if (ImGui::Button("Default tracepoints") && ctx->connection) { gputop_client_context_add_tracepoint(ctx, "drm/drm_vblank_event"); gputop_client_context_add_tracepoint(ctx, "i915/i915_request_add"); gputop_client_context_add_tracepoint(ctx, "i915/i915_request_retire"); } display_cpu_stats(); /* GPU */ ImGui::Separator(); if (ctx->features) { const struct gputop_devinfo *devinfo = &ctx->devinfo; ImGui::Text("GT name: %s (Gen %u, PCI 0x%x)", devinfo->prettyname, devinfo->gen, devinfo->devid); ImGui::Text("%" PRIu64 " threads, %" PRIu64 " EUs, %" PRIu64 " slices, %" PRIu64 " subslices", devinfo->eu_threads_count, devinfo->n_eus, devinfo->n_eu_slices, devinfo->n_eu_sub_slices); ImGui::Text("GT frequency range %.1fMHz / %.1fMHz", (double) devinfo->gt_min_freq / 1000000.0f, (double) devinfo->gt_max_freq / 1000000.0f); ImGui::Text("CS timestamp frequency %" PRIu64 " Hz / %.2f ns", devinfo->timestamp_frequency, 1000000000.0f / devinfo->timestamp_frequency); ImGui::Text("RCS busyness:"); ImGui::SameLine(); ImGui::ProgressBar(gputop_client_context_calc_busyness(ctx), ImVec2(ImGui::GetContentRegionAvailWidth(), 0.0f)); bool open_popup = ImGui::Button("Select metric"); if (open_popup) ImGui::OpenPopup("metric picker"); ImGui::SetNextWindowSize(ImVec2(400, 400)); if (ImGui::BeginPopup("metric picker")) { if (select_metric_set(ctx, &ctx->metric_set)) { maybe_restart_sampling(ctx); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } ImGui::SameLine(); open_popup = ImGui::Button("Select metric set from counter"); if (open_popup) ImGui::OpenPopup("metric counter picker"); ImGui::SetNextWindowSize(ImVec2(600, 400)); if (ImGui::BeginPopup("metric counter picker")) { if (select_metric_set_from_counter(ctx, &ctx->metric_set)) { maybe_restart_sampling(ctx); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } ImGui::SameLine(); ImColor color = ctx->metric_set ? ImColor(0.0f, 1.0f, 0.0f) : ImColor(0.9f, 0.0f, 0.0f); ImGui::TextColored(color, "%s", ctx->metric_set ? ctx->metric_set->name : "No metric set selected"); } int oa_sampling_period_ms = ctx->oa_aggregation_period_ns / 1000000ULL; if (ImGui::InputInt("OA sampling period (ms)", &oa_sampling_period_ms)) ctx->oa_aggregation_period_ns = CLAMP(oa_sampling_period_ms, 1, 1000) * 1000000ULL; uint64_t oa_sampling_period_ns = 0ULL; if (select_oa_exponent(ctx, &oa_sampling_period_ns)) ctx->oa_sampling_period_ns = oa_sampling_period_ns; ImGui::SameLine(); char pretty_bandwidth[20]; gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_BYTES, gputop_i915_perf_record_max_size(&ctx->i915_perf_config) * (1000000000ULL / ctx->oa_sampling_period_ns), pretty_bandwidth, sizeof(pretty_bandwidth)); char pretty_sampling[20]; gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, ctx->oa_sampling_period_ns, pretty_sampling, sizeof(pretty_sampling)); ImGui::Text("OA sampling at %s, bandwidth from server: %s/s", pretty_sampling, pretty_bandwidth); ImGui::SliderFloat("OA visible sampling (s)", &ctx->oa_visible_timeline_s, 0.1f, 15.0f); if (StartStopSamplingButton(ctx)) { toggle_start_stop_sampling(ctx); } ImGui::SameLine(); if (ImGui::Button("Live counters")) { show_live_i915_perf_counters_window(); } ImGui::SameLine(); if (ImGui::Button("Live usage")) { show_live_i915_perf_usage_window(); } ImGui::Text("Timelines:"); ImGui::SameLine(); if (ImGui::Button("Global")) { show_global_i915_perf_window(); } ImGui::SameLine(); if (ImGui::Button("Per contexts")) { show_contexts_i915_perf_window(); } ImGui::SameLine(); if (ImGui::Button("Multi contexts")) { show_timeline_window(); } if (ctx->features) { static bool show_topology = true; ImGui::Checkbox("Show topology", &show_topology); if (show_topology) { ImGui::BeginChild("##topology"); const Gputop__DevInfo *devinfo = ctx->features->features->devinfo; const char *engine_names[] = { "other", "rcs", "blt", "vcs", "vecs", }; assert(devinfo->topology->n_engines <= ARRAY_SIZE(engine_names)); Gputop::EngineTopology("##engines", devinfo->topology->n_engines, devinfo->topology->engines, engine_names, ImGui::GetWindowContentRegionWidth()); Gputop::RcsTopology("##topology", devinfo->topology->max_slices, devinfo->topology->max_subslices, devinfo->topology->max_eus_per_subslice, devinfo->topology->slices_mask.data, devinfo->topology->subslices_mask.data, devinfo->topology->eus_mask.data, ImGui::GetWindowContentRegionWidth()); ImGui::EndChild(); } } } static void show_main_window(void) { struct window *window = &context.main_window; if (window->opened) return; snprintf(window->name, sizeof(window->name), "GPUTop"); window->size = ImVec2(-1, 600); window->position = ImVec2(0, 0); window->opened = true; window->display = display_main_window; window->destroy = NULL; list_add(&window->link, &context.windows); } /**/ static void display_windows(void) { list_for_each_entry(struct window, window, &context.windows, link) { ImGui::SetNextWindowPos(window->position, ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(window->size, ImGuiCond_FirstUseEver); ImGui::Begin(window->name, &window->opened); window->display(window); window->position = ImGui::GetWindowPos(); window->size = ImGui::GetWindowSize(); ImGui::End(); } list_for_each_entry_safe(struct window, window, &context.windows, link) { if (window->opened) continue; if (window->destroy) { list_del(&window->link); window->destroy(window); } else window->opened = true; } } static void init_ui(const char *host, int port) { memset(&context.ctx, 0, sizeof(context.ctx)); list_inithead(&context.windows); ImGuiIO& io = ImGui::GetIO(); io.NavFlags |= ImGuiNavFlags_EnableKeyboard; context.clear_color = ImColor(114, 144, 154); Gputop::InitColorsProperties(); gputop_client_context_init(&context.ctx); snprintf(context.host_address, sizeof(context.host_address), "%s", host ? host : "localhost"); context.host_port = port != 0 ? port : 7890; if (host != NULL) reconnect(); } /**/ #ifdef EMSCRIPTEN static void repaint_window(void *user_data) { SDL_Event event; while (SDL_PollEvent(&event)) { ImGui_ImplSdlGLES2_ProcessEvent(&event); } ImGui_ImplSdlGLES2_NewFrame(context.window); show_main_window(); display_windows(); glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); glClearColor(context.clear_color.x, context.clear_color.y, context.clear_color.z, 1.0); glClear(GL_COLOR_BUFFER_BIT); ImGui::Render(); ImGui_ImplSdlGLES2_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(context.window); } extern "C" EMSCRIPTEN_KEEPALIVE void resize_window_callback(int width, int height) { SDL_SetWindowSize(context.window, width, height); } #elif defined(GPUTOP_UI_GTK) static void repaint_window(CoglOnscreen *onscreen, void *user_data) { ImGui_ImplGtk3Cogl_NewFrame(); show_main_window(); display_windows(); /* Rendering */ { CoglFramebuffer *fb = COGL_FRAMEBUFFER(onscreen); cogl_framebuffer_set_viewport(fb, 0, 0, cogl_framebuffer_get_width(fb), cogl_framebuffer_get_height(fb)); cogl_framebuffer_clear4f(fb, COGL_BUFFER_BIT_COLOR | COGL_BUFFER_BIT_DEPTH, context.clear_color.x, context.clear_color.y, context.clear_color.z, 1.0); ImGui::Render(); ImGui_ImplGtk3Cogl_RenderDrawData(ImGui::GetDrawData()); cogl_onscreen_swap_buffers(onscreen); } } #elif defined(GPUTOP_UI_GLFW) static void repaint_window(void *user_data) { if (glfwWindowShouldClose(context.window)) { ImGui_ImplGlfwGL3_Shutdown(); glfwTerminate(); uv_stop(uv_default_loop()); return; } ImGui_ImplGlfwGL3_NewFrame(); show_main_window(); display_windows(); int display_w, display_h; glfwGetFramebufferSize(context.window, &display_w, &display_h); glViewport(0, 0, display_w, display_h); glClearColor(context.clear_color.x, context.clear_color.y, context.clear_color.z, 1.0); glClear(GL_COLOR_BUFFER_BIT); ImGui::Render(); ImGui_ImplGlfwGL3_RenderDrawData(ImGui::GetDrawData()); glfwSwapBuffers(context.window); } #endif /* Native part */ int main(int argc, char *argv[]) { #ifdef EMSCRIPTEN /* Setup SDL */ if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; } /* Setup window */ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, ¤t); context.window = SDL_CreateWindow("GPUTop", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE); SDL_GL_CreateContext(context.window); ImGui::CreateContext(); ImGui_ImplSdlGLES2_Init(context.window, repaint_window, NULL); char host[128]; memset(host, 0, sizeof(host)); EM_ASM({ var uriParams = new URLSearchParams(window.location.search); if (!uriParams.has('remoteHost')) return; var host = uriParams.get('remoteHost'); var numBytesWritten = stringToUTF8(host, $0, $1); }, host, sizeof(host)); int port = EM_ASM_INT({ var uriParams = new URLSearchParams(window.location.search); if (!uriParams.has('remotePort')) return 0; return parseInt(uriParams.get('remotePort')); }); EM_ASM({ var resizeFunc = function() { Module['_resize_window_callback'](window.innerWidth, window.innerHeight); }; window.addEventListener("resize", resizeFunc); resizeFunc(); }, context.window); init_ui(host[0] != '\0' ? host : NULL, port); #elif defined(GPUTOP_UI_GTK) g_autofree gchar *host = NULL; GOptionEntry entries[] = { { "host", 'h', 0, G_OPTION_ARG_STRING, &host, "Connect a host", "hostname", }, { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL, }, }; gtk_init(&argc, &argv); g_autoptr(GOptionContext) context = NULL; context = g_option_context_new(NULL); g_option_context_set_ignore_unknown_options(context, TRUE); g_option_context_set_help_enabled(context, FALSE); g_option_context_add_main_entries(context, entries, NULL); g_option_context_parse(context, &argc, &argv, NULL); GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "GPUTop"); g_signal_connect(window, "delete-event", G_CALLBACK(gtk_main_quit), NULL); gtk_window_resize(GTK_WINDOW(window), 1280, 720); GtkWidget *box = gtk_event_box_new(); gtk_widget_set_can_focus(box, TRUE); gtk_container_add(GTK_CONTAINER(window), box); gtk_widget_show_all(window); ImGui::CreateContext(); ImGui_ImplGtk3Cogl_Init(box, repaint_window, NULL); if (host) { g_autofree gchar *url = g_strdup_printf("gputop://%s", host); g_autoptr(SoupURI) uri = soup_uri_new(url); init_ui(soup_uri_get_host(uri), soup_uri_get_port(uri)); } else init_ui(NULL, 0); gtk_main(); ImGui::DestroyContext(); #elif defined(GPUTOP_UI_GLFW) const struct option long_options[] = { { "host", required_argument, 0, 'h' }, { 0, 0, 0, 0 } }; char *host = NULL; int opt, port = 0; while ((opt = getopt_long(argc, argv, "h:", long_options, NULL)) != -1) { switch (opt) { case 'h': { char *port_str; if ((port_str = strstr(optarg, ":")) != NULL) { host = (char *) calloc(port_str - optarg, sizeof(char)); memcpy(host, optarg, port_str - optarg); port = atoi(port_str + 1); } break; } } } if (!glfwInit()) return -1; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); context.window = glfwCreateWindow(1280, 720, "GPUTop", NULL, NULL); glfwMakeContextCurrent(context.window); glfwSwapInterval(1); // Enable vsync ImGui::CreateContext(); if (!ImGui_ImplGlfwGL3_Init(context.window, repaint_window, NULL)) return -1; init_ui(host, port); uv_run(uv_default_loop(), UV_RUN_DEFAULT); ImGui::DestroyContext(); #endif return EXIT_SUCCESS; } ================================================ FILE: ui/gputop-ui-multilines.cpp ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui.h" #include "imgui_internal.h" #include "gputop-ui-multilines.h" #include "gputop-ui-utils.h" using namespace ImGui; using namespace Gputop; static void PlotMultilinesEx(const char* label, float (*values_getter)(void* data, int line, int idx), void* data, int lines, int values_count, int values_offset, const ImColor *colors, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImVec2 label_size = CalcTextSize(label, NULL, true); if (graph_size.x == 0.0f) graph_size.x = CalcItemWidth(); if (graph_size.y == 0.0f) graph_size.y = label_size.y + (style.FramePadding.y * 2); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); 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)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, window->GetID(label))) return; const bool hovered = ItemHoverable(inner_bb, 0); // Determine scale from values if not specified if (scale_min == FLT_MAX || scale_max == FLT_MAX) { float v_min = FLT_MAX; float v_max = -FLT_MAX; for (int i = 0; i < values_count; i++) { const float v = values_getter(data, 0, i); v_min = ImMin(v_min, v); v_max = ImMax(v_max, v); } if (scale_min == FLT_MAX) scale_min = v_min; if (scale_max == FLT_MAX) scale_max = v_max; } RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); if (values_count > 0) { int res_w = ImMin((int)graph_size.x, values_count) -1; int item_count = values_count -1; // Tooltip on hover int v_hovered = -1; int v_idx = -1; if (hovered) { const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); v_idx = (int)(t * item_count); IM_ASSERT(v_idx >= 0 && v_idx < values_count); BeginTooltip(); for (int l = 0; l < lines; l++) { const float v0 = values_getter(data, l, (v_idx + values_offset) % values_count); const float v1 = values_getter(data, l, (v_idx + 1 + values_offset) % values_count); ColorButton("", colors[l], ImGuiColorEditFlags_NoInputs); SameLine(); Text("%d: %d: %8.4g - %d: %8.4g", l, v_idx, v0, v_idx+1, v1); } EndTooltip(); v_hovered = v_idx; } const float t_step = 1.0f / (float)res_w; for (int l = 0; l < lines; l++) { float v0 = values_getter(data, l, (0 + values_offset) % values_count); float t0 = 0.0f; ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle for (int n = 0; n < res_w; n++) { const float t1 = t0 + t_step; 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, l, (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, tp1); window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? colors[l] : colors[l]); t0 = t1; tp0 = tp1; } } if (hovered) { ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, ImVec2(t_step * (v_idx + 0.5f), 0.0f)); ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, ImVec2(t_step * (v_idx + 0.5f), 1.0f)); window->DrawList->AddLine(pos0, pos1, GetColor(GputopCol_MultilineHover)); } } // Text overlay if (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)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); } void Gputop::PlotMultilines(const char* label, float (*values_getter)(void* data, int line, int idx), void* data, int lines, int values_count, int values_offset, const ImColor *colors, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { PlotMultilinesEx(label, values_getter, data, lines, values_count, values_offset, colors, overlay_text, scale_min, scale_max, graph_size); } ================================================ FILE: ui/gputop-ui-multilines.h ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __GPUTOP_UI_MULTILINES_H__ #define __GPUTOP_UI_MULTILINES_H__ #include #include "imgui.h" namespace Gputop { void PlotMultilines(const char* label, float (*values_getter)(void* data, int line, int idx), void* data, int lines, int values_count, int values_offset, const ImColor *colors, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); } // namespace Gputop #endif /* __GPUTOP_UI_MULTILINES_H__ */ ================================================ FILE: ui/gputop-ui-piechart.cpp ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui.h" #include "imgui_internal.h" #include "gputop-ui-piechart.h" #include "gputop-ui-utils.h" #include using namespace ImGui; using namespace Gputop; static bool in_circle(const ImVec2& center, float radius, const ImVec2& mouse) { const double a = mouse.x - center.x, b = mouse.y - center.y; return sqrt(a * a + b * b) <= radius; } static ImVec2 pie_center = ImVec2(0.0f, 0.0f); static float pie_radius = 0.0f; static float pie_focus_pos = -1.0f; static float pie_accumulated_pos = 0.0f; static int pie_i_value = 0; static int pie_n_values = 1; void Gputop::BeginPieChart(int n_values, ImVec2 graph_size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; if (graph_size.x == 0.0f) graph_size.x = CalcItemWidth(); if (graph_size.y == 0.0f) graph_size.y = graph_size.x; pie_radius = graph_size.x / 2; pie_i_value = 0; pie_n_values = n_values; pie_accumulated_pos = 0.0f; const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); pie_center = total_bb.GetCenter(); ItemSize(total_bb, 0); if (!ItemAdd(total_bb, 0)) return; ImGuiContext& g = *GImGui; const ImVec2 mouse(g.IO.MousePos); if (ItemHoverable(total_bb, 0) && in_circle(pie_center, pie_radius, mouse)) { if (mouse.x <= pie_center.x) { if (mouse.y <= pie_center.y) // left-top pie_focus_pos = atan((pie_center.y - mouse.y) / (pie_center.x - mouse.x)); else // left-bottom pie_focus_pos = 3 * M_PI / 2 + atan((pie_center.x - mouse.x) / (mouse.y - pie_center.y)); } else { if (mouse.y <= pie_center.y) // right-top pie_focus_pos = M_PI / 2 + atan((mouse.x - pie_center.x) / (pie_center.y - mouse.y)); else // right-bottom pie_focus_pos = M_PI + atan((mouse.y - pie_center.y) / (mouse.x - pie_center.x)); } } else pie_focus_pos = -1.0f; } bool Gputop::PieChartItem(float value) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; assert(value <= 1.0f); const float max_sides = 60; const float start = pie_accumulated_pos * 2 * M_PI; const float end = (pie_accumulated_pos + value) * 2 * M_PI; const bool hovered = (pie_focus_pos >= start && pie_focus_pos <= end); assert(pie_i_value < pie_n_values); window->DrawList->PathLineTo(pie_center); window->DrawList->PathArcTo(pie_center, pie_radius, M_PI + start, M_PI + end, ImMax(value * max_sides, 4.0f)); window->DrawList->PathLineTo(pie_center); window->DrawList->PathFillConvex(GetHueColor(pie_i_value, pie_n_values, hovered ? 0.8f : 0.5f)); pie_accumulated_pos += value; pie_i_value++; return hovered; } void Gputop::EndPieChart() { pie_i_value = 0; pie_n_values = 0; pie_accumulated_pos = 0.0f; } ================================================ FILE: ui/gputop-ui-piechart.h ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __GPUTOP_UI_PIECHART_H__ #define __GPUTOP_UI_PIECHART_H__ #include #include "imgui.h" namespace Gputop { void BeginPieChart(int n_values, ImVec2 graph_size = ImVec2(0,0)); bool PieChartItem(float value); void EndPieChart(); } // namespace Gputop #endif /* __GPUTOP_UI_PIECHART_H__ */ ================================================ FILE: ui/gputop-ui-plots.cpp ================================================ /* * GPU Top * * Copyright (C) 2018 Intel Corporation * Copyright (c) 2014-2017 Omar Cornut and ImGui contributors * * Code copied & modified from ImGui (imgui.cpp). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui.h" #include "imgui_internal.h" #include "gputop-ui-plots.h" #include "gputop-ui-utils.h" using namespace ImGui; using namespace Gputop; static int PlotExV(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, int value_highlight, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return -1; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImVec2 label_size = CalcTextSize(label, NULL, true); if (graph_size.x == 0.0f) graph_size.x = CalcItemWidth(); if (graph_size.y == 0.0f) graph_size.y = label_size.y + (style.FramePadding.y * 2); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); 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)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, 0, &frame_bb)) return -1; const bool hovered = ItemHoverable(inner_bb, 0); // Determine scale from values if not specified if (scale_min == FLT_MAX || scale_max == FLT_MAX) { float v_min = FLT_MAX; float v_max = -FLT_MAX; for (int i = 0; i < values_count; i++) { const float v = values_getter(data, i); v_min = ImMin(v_min, v); v_max = ImMax(v_max, v); } if (scale_min == FLT_MAX) scale_min = v_min; if (scale_max == FLT_MAX) scale_max = v_max; } RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); int v_hovered = -1; if (values_count > 0) { 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 if (hovered) { 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 * 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) SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); else if (plot_type == ImGuiPlotType_Histogram) SetTooltip("%d: %8.4g", v_idx, v0); v_hovered = v_idx; } const float t_step = 1.0f / (float)res_w; const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min)); float v0 = values_getter(data, (0 + values_offset) % values_count); float t0 = 0.0f; ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands const ImU32 col_base = GetColor((plot_type == ImGuiPlotType_Lines) ? GputopCol_PlotLines : GputopCol_PlotHistogram); const ImU32 col_hovered = GetColor((plot_type == ImGuiPlotType_Lines) ? GputopCol_PlotLinesHovered : GputopCol_PlotHistogramHovered); for (int n = 0; n < res_w; n++) { const float t1 = t0 + t_step; 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) * inv_scale) ); const ImU32 color = (v_hovered == v1_idx || value_highlight == v1_idx) ? col_hovered : col_base; // 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, histogram_zero_line_t)); if (plot_type == ImGuiPlotType_Lines) { window->DrawList->AddLine(pos0, pos1, color); } else if (plot_type == ImGuiPlotType_Histogram) { if (pos1.x >= pos0.x + 2.0f) pos1.x -= 1.0f; window->DrawList->AddRectFilled(pos0, pos1, color); } t0 = t1; tp0 = tp1; } } // Text overlay if (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)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); return v_hovered; } struct ImGuiPlotArrayGetterData { const float* Values; int Stride; ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } }; static float Plot_ArrayGetter(void* data, int idx) { ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); return v; } int Gputop::PlotLines(const char* label, const float* values, int values_count, int values_offset, int value_highlight, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); return PlotExV(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, value_highlight, overlay_text, scale_min, scale_max, graph_size); } int Gputop::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, int value_highlight, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { return PlotExV(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, value_highlight, overlay_text, scale_min, scale_max, graph_size); } int Gputop::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, int value_highlight, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); return PlotExV(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, value_highlight, overlay_text, scale_min, scale_max, graph_size); } int Gputop::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, int value_highlight, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { return PlotExV(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, value_highlight, overlay_text, scale_min, scale_max, graph_size); } ================================================ FILE: ui/gputop-ui-plots.h ================================================ /* * GPU Top * * Copyright (C) 2018 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __GPUTOP_UI_PLOTS_H__ #define __GPUTOP_UI_PLOTS_H__ #include "imgui.h" namespace Gputop { int PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, int value_highlight = -1, 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)); int PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, int value_highlight = -1, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); int PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, int value_highlight = -1, 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)); int PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, int value_highlight = -1, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); }; #endif /* __GPUTOP_UI_PLOTS_H__ */ ================================================ FILE: ui/gputop-ui-timeline.cpp ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define IMGUI_DEFINE_MATH_OPERATORS #include #include "imgui.h" #include "imgui_internal.h" #include "gputop-ui-timeline.h" #include "gputop-ui-utils.h" #include "util/macros.h" using namespace ImGui; using namespace Gputop; static int timeline_n_events = 1; static int timeline_n_rows = 1; static float timeline_row_height = 1; static ImRect timeline_inner_bb; static ImRect timeline_frame_bb; static uint64_t timeline_length = 1; static ImVec2 timeline_zoom_pos = ImVec2(-1.0f, -1.0f); static ImVec2 timeline_range_pos = ImVec2(-1.0f, -1.0f); static ImGuiID timeline_id = 0; static bool timeline_item_hovered = false; static float timeline_last_item_pos = -1.0f; static float timeline_last_event_pos = -1.0f; static bool RangeDragBehavior(const ImRect& frame_bb, ImGuiID id, ImVec2* v, bool prev_in_zoom, bool modifier) { ImGuiContext& g = *GImGui; bool in_zoom = false; // Process clicking on the drag if (g.ActiveId == id) { if (modifier && g.IO.MouseClicked[0]) { // Lock current value on click v->x = ImClamp(g.IO.MousePos.x, frame_bb.GetTL().x, frame_bb.GetBR().x); v->y = v->x; in_zoom = true; } else { if (prev_in_zoom) { v->y = ImClamp(g.IO.MousePos.x, frame_bb.GetTL().x, frame_bb.GetBR().x); in_zoom = !g.IO.MouseReleased[0]; } } } return in_zoom; } static bool DragBehavior(const ImRect& frame_bb, ImGuiID id, ImVec2* v) { ImGuiContext& g = *GImGui; bool in_drag = false; // Process clicking on the drag if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { *v = g.IO.MouseDelta; in_drag = true; } } return in_drag; } static bool IsTimelineItemHovered(const ImRect& rect) { ImGuiContext& g = *GImGui; return IsWindowHovered() && rect.Contains(g.IO.MousePos); } void Gputop::BeginTimeline(const char *label, int rows, int events, uint64_t length, ImVec2 timeline_size) { timeline_length = length; ImGuiWindow* window = GetCurrentWindow(); ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float ruler_height = 5.0f; /* TODO: Ruler */ const ImVec2 label_size = CalcTextSize("99999"); /* Top & bottom labels */ const float default_row_height = label_size.y; /* TODO: make this configurable */ if (timeline_size.x == 0.0f) timeline_size.x = CalcItemWidth(); if (timeline_size.y == 0.0f) timeline_size.y = ruler_height + (label_size.y * 2) + rows * default_row_height; timeline_id = window->GetID(label); BeginChildFrame(timeline_id, timeline_size); window = GetCurrentWindow(); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + timeline_size - ImVec2(2.0f, 2.0f) * style.FramePadding); const ImRect inner_bb(frame_bb.Min + ImVec2(0, ruler_height + label_size.y), frame_bb.Max - ImVec2(0, label_size.y)); timeline_frame_bb = frame_bb; timeline_inner_bb = inner_bb; timeline_row_height = inner_bb.GetHeight() / rows; timeline_n_rows = rows; timeline_n_events = events; timeline_item_hovered = false; timeline_last_event_pos = -1.0f; timeline_last_item_pos = -1.0f; } bool Gputop::TimelineItem(int row, uint64_t start, uint64_t end, bool selected) { ImColor color(GetHueColor(row, timeline_n_rows)); ImGuiWindow* window = GetCurrentWindow(); double width = timeline_inner_bb.GetWidth(); ImRect item(timeline_inner_bb.GetTL().x + (double) start * width / timeline_length, timeline_inner_bb.GetTL().y + timeline_row_height * row, timeline_inner_bb.GetTL().x + (double) end * width / timeline_length, timeline_inner_bb.GetTL().y + timeline_row_height * (row + 1)); const bool should_draw = item.GetWidth() >= 1.0f || fabs(timeline_last_item_pos - item.GetTL().x) >= 0.75; if (should_draw) { window->DrawList->AddRectFilled(item.GetTL(), item.GetBR(), color); if (selected) window->DrawList->AddRect(item.GetTL(), item.GetBR(), GetColorU32(ImGuiCol_Text)); timeline_last_item_pos = item.GetTL().x; } const bool hovered = IsTimelineItemHovered(item); if (hovered) timeline_item_hovered = true; return hovered; } bool Gputop::TimelineCustomEvent(uint64_t time, const ImColor& color, bool selected) { ImGuiWindow* window = GetCurrentWindow(); double width = timeline_inner_bb.GetWidth(); double pos = timeline_inner_bb.GetTL().x + (double) time * width / timeline_length; float top = timeline_inner_bb.GetTL().y, bottom = timeline_inner_bb.GetBL().y; ImRect item(pos, top, pos, bottom); const bool should_draw = fabs(timeline_last_event_pos - pos) >= 0.75; if (should_draw) { window->DrawList->AddLine(item.GetTL(), item.GetBR(), color); timeline_last_event_pos = pos; } item.Expand(ImVec2(3.0f, 0.0f)); ImGuiContext& g = *GImGui; const bool hovered = IsTimelineItemHovered(item); if ((should_draw && hovered && !timeline_item_hovered) || selected) { window->DrawList->AddCircleFilled(ImVec2(item.GetTL().x + 2.0f, ImClamp(g.IO.MousePos.y, top, bottom)), 5.0f, GetColor(GputopCol_TimelineEventSelect)); timeline_item_hovered = true; } return hovered; } bool Gputop::TimelineEvent(int event, uint64_t time, bool selected) { return Gputop::TimelineCustomEvent(time, GetHueColor(event, timeline_n_events), selected); } static void DrawRange(const ImVec2& range, const char **units, int n_units) { ImGuiWindow* window = GetCurrentWindow(); ImRect rect(ImMin(range.x, range.y), timeline_frame_bb.GetTL().y, ImMax(range.x, range.y), timeline_frame_bb.GetBR().y); window->DrawList->AddRectFilledMultiColor(rect.GetTL(), rect.GetBR(), GetColor(GputopCol_TimelineZoomLeft), GetColor(GputopCol_TimelineZoomRight), GetColor(GputopCol_TimelineZoomRight), GetColor(GputopCol_TimelineZoomLeft)); float tl_start = timeline_inner_bb.GetTL().x; float tl_width = timeline_inner_bb.GetWidth(); double range_length = (double) timeline_length * (ImMax(range.x, range.y) - tl_start) / tl_width - (double) timeline_length * (ImMin(range.x, range.y) - tl_start) / tl_width; int unit_idx = 0; while (range_length >= 1000.0f && unit_idx < (n_units - 1)) { range_length /= 1000.0f; unit_idx++; } char range_str[20]; snprintf(range_str, sizeof(range_str), "%.3f%s", range_length, units[unit_idx]); const ImVec2 label_size = CalcTextSize(range_str); window->DrawList->AddLine(rect.GetBL() - ImVec2(0, label_size.y), rect.GetBR() - ImVec2(0, label_size.y), GetColorU32(ImGuiCol_Text)); window->DrawList->AddText(ImVec2((rect.GetBL().x + rect.GetBR().x) / 2, rect.GetBL().y) - ImVec2(label_size.x / 2, label_size.y), GetColorU32(ImGuiCol_Text), range_str); } #ifndef ALIGN #define ALIGN(x, align) (((x) % (align)) == 0 ? (x) : ((x) + ((align) - (x) % (align)))) #endif static float ToPixelSize(uint64_t value) { return (double) timeline_inner_bb.GetWidth() * value / timeline_length; } static uint64_t ToLength(float value) { return (double) value * timeline_length / timeline_inner_bb.GetWidth(); } static uint64_t NextLength(uint64_t value) { if (value % 2 == 0) return value / 2; if (value % 5 == 0) return value / 5; return 0; } bool Gputop::EndTimeline(const char **units, int n_units, const char **row_labels, int64_t *zoom_start, uint64_t *zoom_end) { ImGuiWindow* window = GetCurrentWindow(); ImGuiContext& g = *GImGui; const bool hovered = IsWindowHovered(); const bool clicked = hovered && IsMouseClicked(0); if (clicked) { SetActiveID(timeline_id, window); FocusWindow(window); } /* Row labels */ if (row_labels) { for (int row = 0; row < timeline_n_rows; row++) { const ImVec2 label_size = CalcTextSize(row_labels[row]); /* Top & bottom labels */ ImVec2 label_pos(timeline_inner_bb.GetTL().x, timeline_inner_bb.GetTL().y + timeline_row_height * row + timeline_row_height / 2 - label_size.y / 2); window->DrawList->AddText(label_pos, GetColorU32(ImGuiCol_Text), row_labels[row]); } } /* Ruler */ { struct { uint64_t divider; bool enabled; uint64_t increment; uint64_t window; float px_increment; } ruler_levels[4] = { { 1ULL, false, 0, 0, 0.0f, }, { 1000ULL, false, 0, 0, 0.0f, }, { 1000000ULL, false, 0, 0, 0.0f, }, { 1000000000ULL, false, 0, 0, 0.0f, } }; const ImVec2 label_size = CalcTextSize("9999999"); const uint64_t label_length = ToLength(label_size.x); uint64_t current_length = timeline_length; for (int u = n_units - 1; u >= 0; u--) { if (ruler_levels[u].divider > current_length || (ruler_levels[u].divider * 500) < label_length) continue; ruler_levels[u].window = ALIGN(current_length, ruler_levels[u].divider); current_length = 1000ULL; while (current_length >= 2 && (NextLength(current_length) * ruler_levels[u].divider) > label_length) current_length = NextLength(current_length); current_length *= ruler_levels[u].divider; ruler_levels[u].enabled = true; ruler_levels[u].increment = current_length; ruler_levels[u].px_increment = ToPixelSize(ruler_levels[u].increment); } /* Now draw at the specified intervals */ bool zero_done = false; for (int u = n_units - 1; u >= 0; u--) { if (!ruler_levels[u].enabled) continue; for (int i = 0; i * ruler_levels[u].px_increment < timeline_inner_bb.Max.x; i++) { if (i == 0 && !zero_done) zero_done = true; else if ((ruler_levels[u].increment * i) % ruler_levels[u].window == 0) continue; float marker_pos = timeline_inner_bb.Min.x + i * ruler_levels[u].px_increment; ImRect line(marker_pos, timeline_frame_bb.Min.y, marker_pos, timeline_frame_bb.Min.y + 5.0f); window->DrawList->AddLine(line.GetTL(), line.GetBR(), ImColor(255, 255, 255)); uint64_t value = ((i * ruler_levels[u].increment) % ruler_levels[u].window) / ruler_levels[u].divider; char ruler_value[20]; snprintf(ruler_value, sizeof(ruler_value), "%" PRIu64 "%s", value, units[u]); window->DrawList->AddText(line.GetBR(), GetColorU32(ImGuiCol_Text), ruler_value); } } } bool zoom_changed = false; bool in_zoom = false; bool in_range = false; bool need_clear = false; static bool last_in_range = false; static bool last_in_zoom = false; if (g.ActiveId == timeline_id) { /* Zoom */ in_zoom = RangeDragBehavior(timeline_inner_bb, timeline_id, &timeline_zoom_pos, last_in_zoom, g.IO.KeyCtrl); if (in_zoom) DrawRange(timeline_zoom_pos, units, n_units); zoom_changed = last_in_zoom && !in_zoom; last_in_zoom = in_zoom; float tl_start = timeline_inner_bb.GetTL().x; float tl_width = timeline_inner_bb.GetWidth(); if (zoom_changed) { if (zoom_start) *zoom_start = (double) timeline_length * (ImMin(timeline_zoom_pos.x, timeline_zoom_pos.y) - tl_start) / tl_width; if (zoom_end) *zoom_end = (double) timeline_length * (ImMax(timeline_zoom_pos.x, timeline_zoom_pos.y) - tl_start) / tl_width; } /* Range */ in_range = RangeDragBehavior(timeline_inner_bb, timeline_id, &timeline_range_pos, last_in_range, g.IO.KeyShift); if (in_range) DrawRange(timeline_range_pos, units, n_units); last_in_range = in_range; if (!last_in_zoom && !last_in_range) need_clear = true; } else { last_in_range = false; last_in_zoom = false; } if (!in_zoom && !in_range && hovered && timeline_inner_bb.Contains(g.IO.MousePos) && g.IO.MouseWheel != 0.0f) { const float scroll_pos((g.IO.MousePos.x - timeline_inner_bb.GetTL().x) / timeline_inner_bb.GetWidth()); const float wheel = fabs(g.IO.MouseWheel) == 1.0f ? (g.IO.MouseWheel * GetProperty(GputopProp_TimelineScrollScaleFactor) / 100.0f) : g.IO.MouseWheel; int64_t delta = timeline_length * wheel; uint64_t length = MAX2(timeline_length - delta, 5ULL); if (length != timeline_length) { int64_t start = delta * scroll_pos; if (zoom_start) *zoom_start = start; if (zoom_end) *zoom_end = start + length; zoom_changed = true; } } ImVec2 drag_offset(0.0f, 0.0f); if (!in_zoom && !in_range && DragBehavior(timeline_inner_bb, timeline_id, &drag_offset)) { int64_t drag_timeline_offset = timeline_length * drag_offset.x / timeline_inner_bb.GetWidth(); if (zoom_start) *zoom_start = -drag_timeline_offset; if (zoom_end) *zoom_end = -drag_timeline_offset + timeline_length; zoom_changed = true; need_clear = false; } if (hovered && !timeline_item_hovered && !in_zoom && !in_range) { SetTooltip("Ctrl-click to zoom\n" "Shift-click to measure"); } if (need_clear) ClearActiveID(); EndChildFrame(); return zoom_changed; } ================================================ FILE: ui/gputop-ui-timeline.h ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __GPUTOP_UI_TIMELINE_H__ #define __GPUTOP_UI_TIMELINE_H__ #include #include "imgui.h" namespace Gputop { enum TimelineAction { TIMELINE_ACTION_NONE, TIMELINE_ACTION_SELECT, TIMELINE_ACTION_DRAG, TIMELINE_ACTION_ZOOM_IN, TIMELINE_ACTION_ZOOM_OUT, }; void BeginTimeline(const char *label, int rows, int events, uint64_t length, ImVec2 timeline_size = ImVec2(0,0)); bool TimelineItem(int row, uint64_t start, uint64_t end, bool selected = false); bool TimelineEvent(int event, uint64_t time, bool selected = false); bool TimelineCustomEvent(uint64_t time, const ImColor& color, bool selected = false); bool EndTimeline(const char **units = NULL, int n_units = 0, const char *row_labels[] = NULL, int64_t *zoom_start = NULL, uint64_t *zoom_end = NULL); }; #endif /* __GPUTOP_UI_TIMELINE_H__ */ ================================================ FILE: ui/gputop-ui-topology.cpp ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui.h" #include "imgui_internal.h" #include "gputop-ui-topology.h" #include "gputop-ui-utils.h" #include "util/macros.h" using namespace ImGui; using namespace Gputop; static bool IsHovered(const ImRect& box) { return ItemHoverable(box, 0); } static bool DrawEu(ImGuiWindow* window, const ImRect& eu_box, bool active, int eu) { window->DrawList->AddRectFilled(eu_box.GetTL(), eu_box.GetBR(), GetColor(active ? GputopCol_TopologyEu : GputopCol_TopologyEuDis), 5); ImGuiContext& g = *GImGui; char name[20]; snprintf(name, sizeof(name), "eu%i", eu); const ImVec2 text_size = CalcTextSize(name, NULL, true); window->DrawList->AddText(g.Font, g.FontSize, eu_box.GetCenter() - text_size / 2, GetColor(GputopCol_TopologyText), name, name + strlen(name)); if (IsHovered(eu_box)) { SetTooltip("Eu%i %s", eu, active ? "available" : "fused off"); return true; } return false; } static bool DrawSubslice(ImGuiWindow* window, int ss_max, int eu_max, const uint8_t *ss_mask, const uint8_t *eus_mask, const ImRect& ss_box, int s, int ss) { bool enabled = (ss_mask[ss / 8] >> (ss % 8) & 1) != 0; window->DrawList->AddRectFilled(ss_box.GetTL(), ss_box.GetBR(), GetColor(enabled ? GputopCol_TopologySubslice : GputopCol_TopologySubsliceDis), 5); if (!enabled) { if (IsHovered(ss_box)) { SetTooltip("Subslice%i fused off", ss); return true; } return false; } window->DrawList->AddRectFilled(ss_box.GetTL(), ss_box.GetBR(), GetColor(GputopCol_TopologySubslice), 5); //int eu_lines = eu_max / 2; int eu_per_line = eu_max / 2; const ImVec2 eu_box_size = ss_box.GetSize() / ImVec2(eu_per_line, eu_max / eu_per_line); bool eu_hovered = false; ImVec2 eu_tl(ss_box.GetTL()); int subslice_stride = DIV_ROUND_UP(eu_max, 8); int slice_stride = ss_max * subslice_stride; for (int eu = 0; eu < eu_max; eu++) { const ImRect eu_box(eu_tl, eu_tl + eu_box_size); ImRect tmp = eu_box; tmp.Expand(-GetProperty(GputopProp_TopologySubsliceSpacing)); eu_hovered |= DrawEu(window, tmp, (eus_mask[slice_stride * s + subslice_stride * ss + eu / 8] >> (eu % 8)) & 1, eu); if (eu == 0 || (eu % eu_per_line) != (eu_per_line - 1)) eu_tl.x += eu_box.GetWidth(); else { eu_tl.x = ss_box.GetTL().x; eu_tl.y += eu_box.GetHeight(); } } if (!eu_hovered && IsHovered(ss_box)) { SetTooltip("Subslice%i available", ss); return true; } return eu_hovered; } static bool DrawSlice(ImGuiWindow* window, int s_max, int ss_max, int eu_max, const uint8_t *s_mask, const uint8_t *ss_mask, const uint8_t *eus_mask, const ImRect& s_box, int s) { window->DrawList->AddRectFilled(s_box.GetTL(), s_box.GetBR(), GetColor(GputopCol_TopologySlice), 5); const int lines = ss_max / 2 + ((ss_max % 2) != 0 ? 1 : 0); const ImVec2 ss_box_size = s_box.GetSize() / ImVec2(2, lines); bool ss_hovered = false; ImVec2 ss_tl(s_box.GetTL()); for (int ss = 0; ss < ss_max; ss++) { const ImRect ss_box(ss_tl, ss_tl + ss_box_size); ImRect tmp(ss_box); tmp.Expand(-GetProperty(GputopProp_TopologySliceSpacing)); ss_hovered |= DrawSubslice(window, ss_max, eu_max, ss_mask, eus_mask, tmp, s, ss); if (ss == 0 || ss % 2 != 1) ss_tl.x += ss_box.GetWidth(); else { ss_tl.x = s_box.GetTL().x; ss_tl.y += ss_box.GetHeight(); } } if (!ss_hovered && IsHovered(s_box)) { SetTooltip("Slice%i", s); return true; } return false; } void Gputop::RcsTopology(const char *label, int s_max, int ss_max, int eu_max, const uint8_t *s_mask, const uint8_t *ss_mask, const uint8_t *eus_mask, float width) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; if (width == 0) width = CalcItemWidth(); ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; ImVec2 s_tl = window->DC.CursorPos; const int lines = ss_max / 2 + ((ss_max % 2) != 0 ? 1 : 0); int s_count = 0; for (int s = 0; s < s_max; s++) s_count += (s_mask[s / 8] >> (s % 8)) & 1; const ImVec2 s_box_size(width, GetProperty(GputopProp_TopologySliceHeight) * lines); const ImVec2 item_size(s_box_size.x, s_count * s_box_size.y); ItemSize(item_size, style.FramePadding.y); if (!ItemAdd(ImRect(s_tl, s_tl + item_size), window->GetID(label))) return; for (int s = 0; s < s_max; s++) { if (!(s_mask[s / 8] >> (s % 8) & 1)) continue; const ImRect s_box(s_tl, s_tl + s_box_size); ImRect tmp(s_box); tmp.Expand(-10); DrawSlice(window, s_max, ss_max, eu_max, s_mask, ss_mask, eus_mask, tmp, s); s_tl.y += s_box.GetHeight(); } } void Gputop::EngineTopology(const char *label, uint32_t n_engines, const uint32_t *engines, const char **names, float width) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; if (width == 0) width = CalcItemWidth(); ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float engine_height = 40.0f; float engines_height = 0.0f; uint32_t engine_count = 0; for (int e = 0; e < n_engines; e++) { engines_height = ImMax(engines[e] * engine_height, engines_height); engine_count += engines[e]; } if (engine_count == 0) return; const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(width, engines_height + style.FramePadding.y * 2)); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); ItemSize(frame_bb, style.FramePadding.y); if (!ItemAdd(frame_bb, window->GetID(label))) return; ImRect class_box(inner_bb.GetTL(), inner_bb.GetTL() + ImVec2(inner_bb.GetWidth() / n_engines, engine_height)); for (uint32_t e = 0; e < n_engines; e++) { ImRect instance_box(class_box); for (uint32_t i = 0; i < engines[e]; i++) { ImRect tmp(instance_box); tmp.Expand(-5); window->DrawList->AddRectFilled(tmp.GetTL(), tmp.GetBR(), GetColor(GputopCol_TopologySlice), 5); char label[20]; snprintf(label, sizeof(label), "%s%i", names[e], i); const ImVec2 label_size = CalcTextSize(label); window->DrawList->AddText(tmp.GetCenter() - label_size / 2, GetColor(GputopCol_TopologyText), label); instance_box.Translate(ImVec2(0.0f, instance_box.GetHeight())); } class_box.Translate(ImVec2(class_box.GetWidth(), 0)); } } ================================================ FILE: ui/gputop-ui-topology.h ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __GPUTOP_UI_TOPOLOGY_H__ #define __GPUTOP_UI_TOPOLOGY_H__ #include #include "imgui.h" namespace Gputop { void RcsTopology(const char *label, int s_max, int ss_max, int eu_max, const uint8_t *s_mask, const uint8_t *ss_mask, const uint8_t *eus_mask, float width = 0.0f); void EngineTopology(const char *label, uint32_t n_engines, const uint32_t *engines, const char **names, float width = 0.0f); }; #endif /* __GPUTOP_UI_TOPOLOGY_H__ */ ================================================ FILE: ui/gputop-ui-utils.cpp ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui.h" #include "imgui_internal.h" #include "gputop-ui-utils.h" using namespace ImGui; namespace Gputop { static struct ColorItem { const char *name; ImVec4 value; } colors[GputopCol_COUNT]; static struct PropertyItem { const char *name; int value; } properties[GputopProp_COUNT]; void InitColorsProperties() { colors[GputopCol_TopologySlice] = (struct ColorItem){ "TopologySlice", ImVec4(0.57f, 0.84f, 0.62f, 1.00f) }; colors[GputopCol_TopologySubslice] = (struct ColorItem){ "TopologySubslice", ImVec4(1.00f, 0.89f, 0.62f, 1.00f) }; colors[GputopCol_TopologySubsliceDis] = (struct ColorItem){ "TopologySubsliceDis", ImVec4(0.65f, 0.62f, 0.62f, 1.00f) }; colors[GputopCol_TopologyEu] = (struct ColorItem){ "TopologyEu", ImVec4(0.77f, 0.65f, 0.97f, 1.00f) }; colors[GputopCol_TopologyEuDis] = (struct ColorItem){ "TopologyEuDis", ImVec4(0.59f, 0.59f, 0.59f, 1.00f) }; colors[GputopCol_TopologyText] = (struct ColorItem){ "TopologyText", ImVec4(0.00f, 0.00f, 0.00f, 1.00f) }; colors[GputopCol_MultilineHover] = (struct ColorItem){ "MultilineHover", ImVec4(1.00f, 0.38f, 0.00f, 1.00f) }; colors[GputopCol_TimelineZoomLeft] = (struct ColorItem){ "TimelineZoomLeft", ImVec4(0.31f, 0.81f, 0.96f, 0.50f) }; colors[GputopCol_TimelineZoomRight] = (struct ColorItem){ "TimelineZoomRight", ImVec4(0.31f, 0.53f, 0.96f, 0.50f) }; colors[GputopCol_TimelineEventSelect] = (struct ColorItem){ "TimelineEventSelect", ImVec4(0.31f, 0.53f, 0.96f, 1.00f) }; colors[GputopCol_TimelineHighlightedTs] = (struct ColorItem){ "TimelineHighlightedTs", ImVec4(0.00f, 1.00f, 0.00f, 1.00f) }; colors[GputopCol_CounterSelectedText] = (struct ColorItem){ "CounterSelectedText", ImVec4(0.31f, 0.53f, 0.96f, 1.00f) }; colors[GputopCol_PlotLines] = (struct ColorItem){ "PlotLines", ImVec4(0.15f, 0.85f, 0.20f, 1.00f) }; colors[GputopCol_PlotLinesHovered] = (struct ColorItem){ "PlotLinesHovered", ImVec4(1.00f, 0.43f, 0.35f, 1.00f) }; colors[GputopCol_PlotHistogram] = (struct ColorItem){ "PlotHistogram", ImVec4(0.90f, 0.70f, 0.00f, 1.00f) }; colors[GputopCol_PlotHistogramHovered] = (struct ColorItem){ "PlotHistogramHovered", ImVec4(0.03f, 0.51f, 0.82f, 1.00f) }; properties[GputopProp_TimelineScrollScaleFactor] = (struct PropertyItem){ "TimelineScrollScaleFactor", 20 }; properties[GputopProp_TopologySliceHeight] = (struct PropertyItem){ "TopologySliceHeight", 70 }; properties[GputopProp_TopologySliceSpacing] = (struct PropertyItem){ "TopologySliceSpacing", 5 }; properties[GputopProp_TopologySubsliceSpacing] = (struct PropertyItem){ "TopologySubsliceSpacing", 5 }; } ImU32 GetColor(enum Colors color) { ImGuiStyle& style = GImGui->Style; ImVec4 c = colors[color].value; c.w *= style.Alpha; return ColorConvertFloat4ToU32(c); } int GetProperty(enum Properties prop) { return properties[prop].value; } void DisplayColorsProperties() { static int output_dest = 0; ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); ImGui::SameLine(); if (ImGui::Button("Copy Colors")) { if (output_dest == 0) ImGui::LogToClipboard(); else ImGui::LogToTTY(); for (int i = 0; i < GputopCol_COUNT; i++) { ImGui::LogText("colors[GputopCol_%s]%*s= (struct ColorItem){ \"%s\",%*sImVec4(%.2ff, %.2ff, %.2ff, %.2ff) };\n", colors[i].name, 23-(int)strlen(colors[i].name), "", colors[i].name, 23-(int)strlen(colors[i].name), "", colors[i].value.x, colors[i].value.y, colors[i].value.z, colors[i].value.w); } for (int i = 0; i < GputopProp_COUNT; i++) { ImGui::LogText("properties[GputopProp_%s]%*s= (struct PropertyItem){ \"%s\",%*s%i };\n", properties[i].name, 26-(int)strlen(properties[i].name), "", properties[i].name, 26-(int)strlen(properties[i].name), "", properties[i].value); } ImGui::LogFinish(); } static ImGuiColorEditFlags alpha_flags = 0; ImGui::RadioButton("Opaque", &alpha_flags, 0); ImGui::SameLine(); ImGui::RadioButton("Alpha", &alpha_flags, ImGuiColorEditFlags_AlphaPreview); ImGui::SameLine(); ImGui::RadioButton("Both", &alpha_flags, ImGuiColorEditFlags_AlphaPreviewHalf); static ImGuiTextFilter filter; filter.Draw("Filter colors", 200); for (int i = 0; i < GputopCol_COUNT; i++) { if (!filter.PassFilter(colors[i].name)) continue; ImGui::ColorEdit4(colors[i].name, (float*)&(colors[i].value), ImGuiColorEditFlags_AlphaBar | alpha_flags); } for (int i = 0; i < GputopProp_COUNT; i++) { if (!filter.PassFilter(colors[i].name)) continue; ImGui::DragInt(colors[i].name, &properties[i].value); } } ImColor GetHueColor(int element, int n_elements, float brightness) { return ImColor::HSV(element * 1.0f / ImMax(1, n_elements), brightness, brightness); } } // namespace Gputop ================================================ FILE: ui/gputop-ui-utils.h ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __GPUTOP_UI_UTILS_H__ #define __GPUTOP_UI_UTILS_H__ #include #include "imgui.h" enum Colors { GputopCol_TopologySlice, GputopCol_TopologySubslice, GputopCol_TopologySubsliceDis, GputopCol_TopologyEu, GputopCol_TopologyEuDis, GputopCol_TopologyText, GputopCol_MultilineHover, GputopCol_TimelineZoomLeft, GputopCol_TimelineZoomRight, GputopCol_TimelineEventSelect, GputopCol_TimelineHighlightedTs, GputopCol_CounterSelectedText, GputopCol_PlotLines, GputopCol_PlotLinesHovered, GputopCol_PlotHistogram, GputopCol_PlotHistogramHovered, GputopCol_COUNT }; enum Properties { GputopProp_TimelineScrollScaleFactor, GputopProp_TopologySliceHeight, GputopProp_TopologySliceSpacing, GputopProp_TopologySubsliceSpacing, GputopProp_COUNT }; namespace Gputop { void InitColorsProperties(); ImU32 GetColor(enum Colors color); int GetProperty(enum Properties prop); void DisplayColorsProperties(); ImColor GetHueColor(int element, int n_elements, float brightness = 0.5); }; #endif /* __GPUTOP_UI_UTILS_H__ */ ================================================ FILE: ui/gputop-ui.css ================================================ body { margin: 0px; } ================================================ FILE: ui/gputop-uv-network.c ================================================ /* * GPU Top * * Copyright (C) 2018 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "gputop-network.h" #include #include #include #include #include "util/macros.h" struct _gputop_connection_t { bool open; uv_tcp_t tcp_handle; uv_connect_t connect_req; uv_write_t write_header_req; const uv_buf_t *read_buf; size_t iread, nread; uv_check_t check_handle; wslay_event_context_ptr wslay_ctx; gputop_on_ready_cb_t ready_cb; gputop_on_data_cb_t data_cb; gputop_on_close_cb_t close_cb; void *user_data; char http_client_header[1024]; char http_server_header[64 * 1024]; }; static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; static int mod_table[] = {0, 2, 1}; static void base64_encode(const uint8_t *data_in, size_t input_length, uint8_t *data_out) { size_t output_length = 4 * ((input_length + 2) / 3); for (int i = 0, j = 0; i < input_length;) { uint32_t octet_a = i < input_length ? (unsigned char)data_in[i++] : 0; uint32_t octet_b = i < input_length ? (unsigned char)data_in[i++] : 0; uint32_t octet_c = i < input_length ? (unsigned char)data_in[i++] : 0; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; data_out[j++] = encoding_table[(triple >> 3 * 6) & 0x3F]; data_out[j++] = encoding_table[(triple >> 2 * 6) & 0x3F]; data_out[j++] = encoding_table[(triple >> 1 * 6) & 0x3F]; data_out[j++] = encoding_table[(triple >> 0 * 6) & 0x3F]; } for (int i = 0; i < mod_table[input_length % 3]; i++) data_out[output_length - 1 - i] = '='; data_out[output_length] = '\0'; } static void on_close_cb(uv_handle_t *handle) { gputop_connection_t *conn = handle->data; wslay_event_context_free(conn->wslay_ctx); free(conn); } static void gputop_connection_end(gputop_connection_t *conn, const char *error) { conn->close_cb(conn, error, conn->user_data); uv_read_stop((uv_stream_t *) &conn->tcp_handle); uv_check_stop(&conn->check_handle); uv_close((uv_handle_t *) &conn->tcp_handle, on_close_cb); } static int on_wslay_genmask_cb(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) { for (size_t i = 0; i < len; i++) buf[i] = rand() & 0xff; return 0; } static void on_wslay_msg_recv_cb(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) { gputop_connection_t *conn = user_data; if (arg->opcode == WSLAY_CONNECTION_CLOSE) { gputop_connection_end(conn, NULL); return; } conn->data_cb(conn, arg->msg, arg->msg_length, conn->user_data); } static ssize_t on_wslay_recv_cb(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, int flags, void *user_data) { gputop_connection_t *conn = user_data; int l; if (!conn->read_buf || conn->iread >= conn->nread) { wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK); return -1; } l = MIN2(len, conn->nread - conn->iread); memcpy(buf, &conn->read_buf->base[conn->iread], l); conn->iread += l; return l; } static ssize_t on_wslay_send_cb(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) { gputop_connection_t *conn = user_data; const uv_buf_t buf = uv_buf_init((char *)data, len); return uv_try_write((uv_stream_t *) &conn->tcp_handle, &buf, 1); } static void on_uv_read_alloc_cb(uv_handle_t *handle, size_t size, uv_buf_t *buf) { gputop_connection_t *conn = handle->data; buf->base = conn->http_server_header; buf->len = sizeof(conn->http_server_header); } static void on_uv_read_cb(uv_stream_t *handle, ssize_t nread, const uv_buf_t *buf) { gputop_connection_t *conn = handle->data; if (!conn->open) { conn->open = true; conn->ready_cb(conn, conn->user_data); return; } if (nread == UV_EOF) { gputop_connection_end(conn, NULL); return; } conn->read_buf = buf; conn->iread = 0; conn->nread = nread; wslay_event_recv(conn->wslay_ctx); conn->read_buf = NULL; conn->iread = 0; } static void on_uv_connect_cb(uv_connect_t* req, int status) { gputop_connection_t *conn = req->handle->data; uv_buf_t buf; if (status != 0) { gputop_connection_end(conn, uv_err_name(status)); return; } uv_read_start((uv_stream_t *) &conn->tcp_handle, on_uv_read_alloc_cb, on_uv_read_cb); buf = uv_buf_init(conn->http_client_header, strlen(conn->http_client_header)); uv_write(&conn->write_header_req, (uv_stream_t *) &conn->tcp_handle, &buf, 1, NULL); } static void on_check_cb(uv_check_t* handle) { gputop_connection_t *conn = handle->data; if (wslay_event_want_write(conn->wslay_ctx)) { if (wslay_event_send(conn->wslay_ctx) != 0) gputop_connection_close(conn); } if (wslay_event_want_read(conn->wslay_ctx)) { if (wslay_event_recv(conn->wslay_ctx) != 0) gputop_connection_close(conn); } } gputop_connection_t * gputop_connect(const char *host, int port, gputop_on_ready_cb_t ready_cb, gputop_on_data_cb_t data_cb, gputop_on_close_cb_t close_cb, void *user_data) { gputop_connection_t *conn = calloc(1, sizeof(gputop_connection_t)); uint8_t ws_key[16]; uint8_t ws_key_b64[100]; struct wslay_event_callbacks callbacks = { on_wslay_recv_cb, on_wslay_send_cb, on_wslay_genmask_cb, NULL, NULL, NULL, on_wslay_msg_recv_cb, }; uv_getaddrinfo_t req; int i; conn->ready_cb = ready_cb; conn->data_cb = data_cb; conn->close_cb = close_cb; wslay_event_context_client_init(&conn->wslay_ctx, &callbacks, conn); uv_tcp_init(uv_default_loop(), &conn->tcp_handle); conn->tcp_handle.data = conn; //uv_stream_set_blocking((uv_stream_t *)&conn->tcp_handle, 0); if (uv_getaddrinfo(uv_default_loop(), &req, NULL, host, NULL, NULL) == 0) { union { struct sockaddr addr; struct sockaddr_in addr4; struct sockaddr_in6 addr6; } s; memcpy(&s.addr6, req.addrinfo->ai_addr, req.addrinfo->ai_addrlen); if (req.addrinfo->ai_family == AF_INET6) { s.addr6.sin6_port = htons(port); } else { s.addr4.sin_port = htons(port); } uv_tcp_connect(&conn->connect_req, &conn->tcp_handle, &s.addr, on_uv_connect_cb); uv_freeaddrinfo(req.addrinfo); } else { struct sockaddr_in addr; uv_ip4_addr("127.0.0.1", port, &addr); uv_tcp_connect(&conn->connect_req, &conn->tcp_handle, (const struct sockaddr*) &addr, on_uv_connect_cb); } for (i = 0; i < ARRAY_SIZE(ws_key); i++) ws_key[i] = rand() % 0xff; base64_encode(ws_key, sizeof(ws_key), ws_key_b64); snprintf(conn->http_client_header, sizeof(conn->http_client_header), "GET /gputop HTTP/1.1\r\n" "Host: %s:%u\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Key: %s\r\n" "Sec-WebSocket-Version: 13\r\n\r\n", host, port, ws_key_b64); uv_check_init(uv_default_loop(), &conn->check_handle); conn->check_handle.data = conn; uv_check_start(&conn->check_handle, on_check_cb); return conn; } void gputop_connection_send(gputop_connection_t *conn, const void *data, size_t len) { struct wslay_event_msg msg; assert(conn != NULL); assert(gputop_connection_connected(conn)); assert(data != NULL && len > 0); msg.opcode = WSLAY_BINARY_FRAME; msg.msg = data; msg.msg_length = len; wslay_event_queue_msg(conn->wslay_ctx, &msg); wslay_event_send(conn->wslay_ctx); } void gputop_connection_close(gputop_connection_t *conn) { assert(conn != NULL); wslay_event_queue_close(conn->wslay_ctx, WSLAY_CODE_NORMAL_CLOSURE, NULL, 0); wslay_event_send(conn->wslay_ctx); } bool gputop_connection_connected(gputop_connection_t *conn) { assert(conn != NULL); return conn->open; } ================================================ FILE: ui/imgui/LICENSE.txt ================================================ The MIT License (MIT) Copyright (c) 2014-2017 Omar Cornut and ImGui contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: ui/imgui/imconfig.h ================================================ //----------------------------------------------------------------------------- // COMPILE-TIME OPTIONS FOR DEAR IMGUI // Most options (memory allocation, clipboard callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO(). //----------------------------------------------------------------------------- // A) You may edit imconfig.h (and not overwrite it when updating imgui, or maintain a patch/branch with your modifications to imconfig.h) // B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h" // Note that options such as IMGUI_API, IM_VEC2_CLASS_EXTRA or ImDrawIdx needs to be defined consistently everywhere you include imgui.h, not only for the imgui*.cpp compilation units. //----------------------------------------------------------------------------- #pragma once //---- 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 define obsolete functions names. Consider enabling from time to time or when updating to reduce likelihood of using already obsolete function/names //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS //---- Don't implement default handlers for Windows (so as not to link with certain functions) //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // Don't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // Don't use and link with ImmGetContext/ImmSetCompositionWindow. //---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty) //---- It is very strongly recommended to NOT disable the demo windows. Please read the comment at the top of imgui_demo.cpp. //#define IMGUI_DISABLE_DEMO_WINDOWS //---- Don't implement ImFormatString(), ImFormatStringV() so you can reimplement them yourself. //#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS //---- Include imgui_user.h at the end of imgui.h as a convenience //#define IMGUI_INCLUDE_IMGUI_USER_H //---- Pack colors to BGRA8 instead of RGBA8 (if you needed to convert from one to another anyway) //#define IMGUI_USE_BGRA_PACKED_COLOR //---- Implement STB libraries in a namespace to avoid linkage conflicts (defaults to global namespace) //#define IMGUI_STB_NAMESPACE ImGuiStb //---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4. // This will be inlined as part of ImVec2 and ImVec4 class declarations. /* #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); } */ //---- Use 32-bit vertex indices (instead of default 16-bit) to allow meshes with more than 64K vertices. Render function needs to support it. #define ImDrawIdx unsigned int //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. /* namespace ImGui { void MyFunction(const char* name, const MyMatrix44& v); } */ ================================================ FILE: ui/imgui/imgui.cpp ================================================ // dear imgui, v1.60 WIP // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. // Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui // Releases change-log at https://github.com/ocornut/imgui/releases // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269 // 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, see Readme. For individuals: https://www.patreon.com/imgui /* Index - MISSION STATEMENT - END-USER GUIDE - PROGRAMMER GUIDE (read me!) - Read first - How to update to a newer version of Dear ImGui - Getting started with integrating Dear ImGui in your code/engine - Using gamepad/keyboard navigation [BETA] - API BREAKING CHANGES (read me when you update!) - ISSUES & TODO LIST - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS - How can I help? - How can I display an image? What is ImTextureID, how does it works? - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on labels and the ID stack. - How can I tell when Dear ImGui wants my mouse/keyboard inputs VS when I can pass them to my application? - How can I load a different font than the default? - How can I easily use icons in my application? - How can I load multiple fonts? - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? - How can I preserve my Dear ImGui context across reloading a DLL? (loss of the global/static variables) - How can I use the drawing facilities without an ImGui window? (using ImDrawList API) - I integrated Dear ImGui in my engine and the text or lines are blurry.. - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. - ISSUES & TODO-LIST - CODE MISSION STATEMENT ================= - Easy to use to create code-driven and data-driven tools - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools - Easy to hack and improve - Minimize screen real-estate usage - Minimize setup and maintenance - Minimize state storage on user side - Portable, minimize dependencies, run on target (consoles, phones, etc.) - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window, opening a tree node for the first time, etc. but a typical frame won't allocate anything) Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: - Doesn't look fancy, doesn't animate - Limited layout features, intricate layouts are typically crafted in code END-USER GUIDE ============== - Double-click on title bar to collapse window. - 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 (double-click to auto fit window to its contents). - Click and drag on any empty space to move window. - TAB/SHIFT+TAB to cycle through keyboard editable fields. - CTRL+Click on a slider or drag box to input value as text. - Use mouse wheel to scroll. - Text editor: - Hold SHIFT or use mouse to select text. - CTRL+Left/Right to word jump. - CTRL+Shift+Left/Right to select words. - CTRL+A our Double-Click to select all. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/ - CTRL+Z,CTRL+Y to undo/redo. - ESCAPE to revert text to its original value. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) - Controls are automatically adjusted for OSX to match standard OSX text editing operations. - Gamepad navigation: see suggested mappings in imgui.h ImGuiNavInput_ PROGRAMMER GUIDE ================ READ FIRST - 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::ShowDemoWindow() for demo code demonstrating most features. - You can learn about immediate-mode gui principles at http://www.johno.se/book/imgui.html or watch http://mollyrocket.com/861 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h) - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it. Please report any issue to the GitHub page! - Try to keep your copy of dear imgui reasonably up to date. GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE - Add the Dear ImGui source files to your projects, using your preferred build system. It is recommended you build the .cpp files as part of your project and not as a library. - You can later customize the imconfig.h file to tweak some compilation time behavior, such as integrating imgui types with your own maths types. - See examples/ folder for standalone sample applications. - You may be able to grab and copy a ready made imgui_impl_*** file from the examples/. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. - Init: retrieve the ImGuiIO structure with ImGui::GetIO() and fill the fields marked 'Settings': at minimum you need to set io.DisplaySize (application resolution). Later on you will fill your keyboard mapping, clipboard handlers, and other advanced features but for a basic integration you don't need to worry about it all. - Init: call io.Fonts->GetTexDataAsRGBA32(...), it will build the font atlas texture, then load the texture pixels into graphics memory. - Every frame: - In your main loop as early a possible, fill the IO fields marked 'Input' (e.g. mouse position, buttons, keyboard info, etc.) - Call ImGui::NewFrame() to begin the frame - You can use any ImGui function you want between NewFrame() and Render() - Call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your io.RenderDrawListFn handler. (Even if you don't render, call Render() and ignore the callback, or call EndFrame() instead. Otherwhise some features will break) - All rendering information are stored into command-lists until ImGui::Render() is called. - Dear ImGui never touches or knows 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 minimal application skeleton may be: // Application init ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = 1920.0f; io.DisplaySize.y = 1280.0f; // TODO: Fill others settings of the io structure later. // 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; io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height); // TODO: At this points you've got the texture data and you need to upload that your your graphic system: MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA) // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'. This will be passed back to your via the renderer. io.Fonts->TexID = (void*)texture; // Application main loop while (true) { // Setup low-level inputs (e.g. on Win32, GetKeyboardState(), or write to those fields from your Windows message loop handlers, etc.) 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; // Call NewFrame(), after this point you can use ImGui::* functions anytime ImGui::NewFrame(); // 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 as well! // Render & swap video buffers ImGui::Render(); MyImGuiRenderFunction(ImGui::GetDrawData()); SwapBuffers(); } // Shutdown ImGui::DestroyContext(); - A minimal render function skeleton may be: void void MyRenderFunction(ImDrawData* draw_data) { // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled // TODO: Setup viewport, orthographic projection matrix // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color. for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui 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 { // The texture for the draw call is specified by pcmd->TextureId. // The vast majority of draw calls with use the imgui texture atlas, which value you have set yourself during initialization. MyEngineBindTexture(pcmd->TextureId); // We are using scissoring to clip some objects. All low-level graphics API supports it. // If your engine doesn't support scissoring yet, you will get some small glitches (some elements outside their bounds) which you can fix later. MyEngineScissor((int)pcmd->ClipRect.x, (int)pcmd->ClipRect.y, (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); // Render 'pcmd->ElemCount/3' indexed triangles. // By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits if your engine doesn't support 16-bits indices. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer); } idx_buffer += pcmd->ElemCount; } } } - The examples/ folders contains many functional implementation of the pseudo-code above. - When calling NewFrame(), the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'io.WantTextInput' flags are updated. They tell you if ImGui intends to use your inputs. So for example, if 'io.WantCaptureMouse' is set you would typically want to hide mouse inputs from the rest of your application. Read the FAQ below for more information about those flags. USING GAMEPAD/KEYBOARD NAVIGATION [BETA] - Ask questions and report issues at https://github.com/ocornut/imgui/issues/787 - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable. - Keyboard: - Set io.NavFlags |= ImGuiNavFlags_EnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeyDown[] + io.KeyMap[] arrays. - When keyboard navigation is active (io.NavActive + NavFlags_EnableKeyboard), the io.WantCaptureKeyboard flag will be set. For more advanced uses, you may want to read from: - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set. - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used). - or query focus information with e.g. IsWindowFocused(), IsItemFocused() etc. functions. Please reach out if you think the game vs navigation input sharing could be improved. - Gamepad: - Set io.NavFlags |= ImGuiNavFlags_EnableGamepad to enable. Fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame(). - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values: 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks. - We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone. Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, maybe a power curve, etc.). - If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved. - Mouse: - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback. - Consoles/Tablet/Phone users: Consider using Synergy host (on your computer) + uSynergy.c (in your console/tablet/phone app) to use your PC mouse/keyboard. - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiNavFlags_MoveMouse flag in io.NavFlags. Enabling ImGuiNavFlags_MoveMouse instructs dear imgui to move your mouse cursor along with navigation movements. When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantMoveMouse' to notify you that it wants the mouse cursor to be moved. When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that. (If you set the ImGuiNavFlags_MoveMouse flag but don't honor 'io.WantMoveMouse' properly, imgui will misbehave as it will see your mouse as moving back and forth.) (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want to set a boolean to ignore your other external mouse positions until the external source is moved again.) 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. - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display. - 2018/02/07 (1.60) - reorganized context handling to be more explicit, - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END. - removed Shutdown() function, as DestroyContext() serve this purpose. - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwhise CreateContext() will create its own font atlas instance. - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts. - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts. - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete). - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete). - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData. - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side. - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete). - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame. - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set. - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete). - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete). - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete). - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete). - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete). - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed. - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up. Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions. - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency. - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg. - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding. - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency. - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it. - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting. - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead! - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete). - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete). - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)". - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)! - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete). - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete). - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency. - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame. - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely. - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete). - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete). - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton(). - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu. - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options. - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))' - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity. - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild(). - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it. - 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 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 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 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. this sequence: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); // became: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // 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 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 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes ISSUES & TODO-LIST ================== See TODO.txt FREQUENTLY ASKED QUESTIONS (FAQ), TIPS ====================================== Q: How can I help? A: - If you are experienced with Dear ImGui and C++, look at the github issues, or TODO.txt and see how you want/can help! - Convince your company to fund development time! Individual users: you can also become a Patron (patreon.com/imgui) or donate on PayPal! See README. - Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc. You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1269). Visuals are ideal as they inspire other programmers. But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions. - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately). Q: How can I display an image? What is ImTextureID, how does it works? A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function. Dear 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. Dear ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use. You may call ImGui::ShowMetricsWindow() to explore active draw lists and visualize/understand how the draw data is generated. It is your responsibility to get textures uploaded to your GPU. Q: Can I have multiple widgets with the same label? Can I have widget without a label? A: Yes. A primer on labels and the ID stack... - Elements that are typically not clickable, such as Text() items don't need an ID. - Interactive widgets require state to be carried over multiple frames (most typically Dear ImGui often needs to remember what is the "active" widget). 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" - 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: Button("OK"); 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. Use "##" to pass a complement to the ID that won't be visible to the end-user. This helps solving the simple collision cases when you know which items are going to be created. 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: Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!) - 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, but windows are uniquely identified by their ID.. Use "###" to pass a label that isn't part of ID: 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", fps); 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++) { PushID(i); Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique) PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj); Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique) PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj->Name); Button("Click"); // Label = "Click", ID = hash of string + "label" (unique) PopID(); } - More example showing that you can stack multiple prefixes into the ID stack: Button("Click"); // Label = "Click", ID = hash of "Click" PushID("node"); Button("Click"); // Label = "Click", ID = hash of "node" + "Click" PushID(my_ptr); Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click" PopID(); PopID(); - Tree nodes implicitly creates a scope for you by calling PushID(). Button("Click"); // Label = "Click", ID = hash of "Click" if (TreeNode("node")) { Button("Click"); // Label = "Click", ID = hash of "node" + "Click" TreePop(); } - 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 (dynamic 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: How can I tell when Dear ImGui wants my mouse/keyboard inputs VS when I can pass them to my application? A: You can read the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'ioWantTextInput' flags from the ImGuiIO structure. - 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.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS). Preferably read the flags after calling ImGui::NewFrame() to avoid them lagging by one frame. But reading those flags before calling NewFrame() is also generally ok, as the bool toggles fairly rarely and you don't generally expect to interact with either Dear ImGui or your application during the same frame when that transition occurs. Dear ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is more accurate and correct than checking if a window is hovered. (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 Dear 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/OTF file you want: ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() Q: How can I easily use icons in my application? A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your strings. Read 'How can I load multiple fonts?' and the file 'misc/fonts/README.txt' for instructions and useful header files. Q: How can I load multiple fonts? A: Use the font atlas to pack them into a single texture: (Read misc/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.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config); // Combine multiple fonts into one (e.g. for icon fonts) ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; ImFontConfig config; config.MergeMode = true; io.Fonts->AddFontDefault(); io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs 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. // Add default Japanese ranges io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need) ImVector ranges; ImFontAtlas::GlyphRangesBuilder builder; builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) builder.AddChar(0x7262); // Add a specific character builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. 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! Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. Text input: it is up to your application to pass the right character code to io.AddInputCharacter(). The applications in examples/ are doing that. For languages using IME, on Windows you can copy the Hwnd of your application to io.ImeWindowHandle. The default implementation of io.ImeSetInputScreenPosFn() on Windows will set your IME position correctly. Q: How can I preserve my Dear ImGui context across reloading a DLL? (loss of the global/static variables) A: Create your own context 'ctx = CreateContext()' + 'SetCurrentContext(ctx)' and your own font atlas 'ctx->GetIO().Fonts = new ImFontAtlas()' so you don't rely on the default globals. Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API) A: - You can create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, push a ImGuiCol_WindowBg with zero alpha, then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows. - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData. Q: I integrated Dear 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 Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. A: You are probably mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height). - 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 create widgets without a Begin()/End() block, they will go in an implicit window called "Debug". - tip: the ImGuiOnceUponAFrame helper will allow 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 call Render() multiple times (e.g for VR renders). - tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui! */ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui_internal.h" #include // toupper, isprint #include // NULL, malloc, free, qsort, atoi #include // vsnprintf, sscanf, printf #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include // intptr_t #else #include // intptr_t #endif #define IMGUI_DEBUG_NAV_SCORING 0 #define IMGUI_DEBUG_NAV_RECTS 0 // Visual Studio warnings #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 // Clang warnings with -Weverything #ifdef __clang__ #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great! #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 (typically 0.0f) is ok. #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 "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. #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 #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 #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false #endif // Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall #ifdef _MSC_VER #define IMGUI_CDECL __cdecl #else #define IMGUI_CDECL #endif //------------------------------------------------------------------------- // Forward Declarations //------------------------------------------------------------------------- static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); static ImFont* GetDefaultFont(); static void SetCurrentWindow(ImGuiWindow* window); static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x); static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y); static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond); static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond); static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond); static ImGuiWindow* FindHoveredWindow(ImVec2 pos); static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); static void CheckStacksSize(ImGuiWindow* window, bool write); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window); static void AddDrawListToDrawData(ImVector* out_render_list, ImDrawList* draw_list); static void AddWindowToDrawData(ImVector* out_render_list, ImGuiWindow* window); static void AddWindowToSortedBuffer(ImVector* out_sorted_windows, ImGuiWindow* window); static ImGuiWindowSettings* AddWindowSettings(const char* name); static void LoadIniSettingsFromDisk(const char* ini_filename); static void LoadIniSettingsFromMemory(const char* buf); static void SaveIniSettingsToDisk(const char* ini_filename); static void SaveIniSettingsToMemory(ImVector& out_buf); static void MarkIniSettingsDirty(ImGuiWindow* window); static ImRect GetViewportRect(); static void ClosePopupToLevel(int remaining); static ImGuiWindow* GetFrontMostModalRootWindow(); 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); namespace ImGui { static void NavUpdate(); static void NavUpdateWindowing(); static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id); static void UpdateMovingWindow(); static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); static void FocusFrontMostActiveWindow(ImGuiWindow* ignore_window); } //----------------------------------------------------------------------------- // Platform dependent default implementations //----------------------------------------------------------------------------- static const char* GetClipboardTextFn_DefaultImpl(void* user_data); static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text); static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); //----------------------------------------------------------------------------- // Context //----------------------------------------------------------------------------- // Current context pointer. Implicitely used by all ImGui functions. Always assumed to be != NULL. // CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext(). // If you use DLL hotreloading you might need to call SetCurrentContext() after reloading code from this file. // ImGui functions are not thread-safe because of this pointer. If you want thread-safety to allow N threads to access N different contexts, you can: // - Change this variable to use thread local storage. You may #define GImGui in imconfig.h for that purpose. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 // - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts) #ifndef GImGui ImGuiContext* GImGui = NULL; #endif // Memory Allocator functions. Use SetAllocatorFunctions() to change them. // If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file. // Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; return malloc(size); } static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; free(ptr); } #else static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; (void)size; IM_ASSERT(0); return NULL; } static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; (void)ptr; IM_ASSERT(0); } #endif static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper; static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper; static void* GImAllocatorUserData = NULL; static size_t GImAllocatorActiveAllocationsCount = 0; //----------------------------------------------------------------------------- // User facing structures //----------------------------------------------------------------------------- ImGuiStyle::ImGuiStyle() { Alpha = 1.0f; // Global alpha applies to everything in ImGui WindowPadding = ImVec2(8,8); // Padding within a window WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested. WindowMinSize = ImVec2(32,32); // Minimum window size WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested. 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). FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested. 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! 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 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. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. ImGui::StyleColorsClassic(this); } // To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you. // Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times. void ImGuiStyle::ScaleAllSizes(float scale_factor) { WindowPadding = ImFloor(WindowPadding * scale_factor); WindowRounding = ImFloor(WindowRounding * scale_factor); WindowMinSize = ImFloor(WindowMinSize * scale_factor); ChildRounding = ImFloor(ChildRounding * scale_factor); PopupRounding = ImFloor(PopupRounding * scale_factor); FramePadding = ImFloor(FramePadding * scale_factor); FrameRounding = ImFloor(FrameRounding * scale_factor); ItemSpacing = ImFloor(ItemSpacing * scale_factor); ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor); TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor); IndentSpacing = ImFloor(IndentSpacing * scale_factor); ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor); ScrollbarSize = ImFloor(ScrollbarSize * scale_factor); ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor); GrabMinSize = ImFloor(GrabMinSize * scale_factor); GrabRounding = ImFloor(GrabRounding * scale_factor); DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor); MouseCursorScale = ImFloor(MouseCursorScale * scale_factor); } ImGuiIO::ImGuiIO() { // Most fields are initialized with zero memset(this, 0, sizeof(*this)); // Settings DisplaySize = ImVec2(-1.0f, -1.0f); DeltaTime = 1.0f/60.0f; IniSavingRate = 5.0f; IniFilename = "imgui.ini"; LogFilename = "imgui_log.txt"; NavFlags = 0x00; MouseDoubleClickTime = 0.30f; MouseDoubleClickMaxDist = 6.0f; for (int i = 0; i < ImGuiKey_COUNT; i++) KeyMap[i] = -1; KeyRepeatDelay = 0.250f; KeyRepeatRate = 0.050f; UserData = NULL; Fonts = NULL; FontGlobalScale = 1.0f; FontDefault = NULL; FontAllowUserScaling = false; DisplayFramebufferScale = ImVec2(1.0f, 1.0f); DisplayVisibleMin = DisplayVisibleMax = ImVec2(0.0f, 0.0f); // Advanced/subtle behaviors #ifdef __APPLE__ OptMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag #else OptMacOSXBehaviors = false; #endif OptCursorBlink = true; // Settings (User Functions) GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; ClipboardUserData = NULL; ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; ImeWindowHandle = NULL; #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS RenderDrawListsFn = NULL; #endif // Input (NB: we already have memset zero the entire structure) MousePos = ImVec2(-FLT_MAX, -FLT_MAX); MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX); 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 < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f; } // Pass in translated ASCII characters for text input. // - with glfw you can get those from the callback set in glfwSetCharCallback() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message void ImGuiIO::AddInputCharacter(ImWchar c) { const int n = ImStrlenW(InputCharacters); if (n + 1 < IM_ARRAYSIZE(InputCharacters)) { InputCharacters[n] = c; 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 //----------------------------------------------------------------------------- #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 _WIN32 #define IM_NEWLINE "\r\n" #else #define IM_NEWLINE "\n" #endif ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p) { ImVec2 ap = p - a; ImVec2 ab_dir = b - a; float ab_len = sqrtf(ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y); ab_dir *= 1.0f / ab_len; float dot = ap.x * ab_dir.x + ap.y * ab_dir.y; if (dot < 0.0f) return a; if (dot > ab_len) return b; return a + ab_dir * dot; } bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p) { 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)); } void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w) { ImVec2 v0 = b - a; ImVec2 v1 = c - a; ImVec2 v2 = p - a; const float denom = v0.x * v1.y - v1.x * v0.y; out_v = (v2.x * v1.y - v1.x * v2.y) / denom; out_w = (v0.x * v2.y - v2.x * v0.y) / denom; out_u = 1.0f - out_v - out_w; } ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p) { ImVec2 proj_ab = ImLineClosestPoint(a, b, p); ImVec2 proj_bc = ImLineClosestPoint(b, c, p); ImVec2 proj_ca = ImLineClosestPoint(c, a, p); float dist2_ab = ImLengthSqr(p - proj_ab); float dist2_bc = ImLengthSqr(p - proj_bc); float dist2_ca = ImLengthSqr(p - proj_ca); float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca)); if (m == dist2_ab) return proj_ab; if (m == dist2_bc) return proj_bc; return proj_ca; } int ImStricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } int ImStrnicmp(const char* str1, const char* str2, size_t count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } void ImStrncpy(char* dst, const char* src, size_t count) { if (count < 1) return; strncpy(dst, src, count); dst[count-1] = 0; } char* ImStrdup(const char *str) { size_t len = strlen(str) + 1; void* buf = ImGui::MemAlloc(len); return (char*)memcpy(buf, (const void*)str, len); } char* ImStrchrRange(const char* str, const char* str_end, char c) { for ( ; str < str_end; str++) if (*str == c) return (char*)str; return NULL; } int ImStrlenW(const ImWchar* str) { int n = 0; while (*str++) n++; return n; } 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_end && *haystack) || (haystack_end && haystack < haystack_end)) { if (toupper(*haystack) == un0) { const char* b = needle + 1; for (const char* a = haystack + 1; b < needle_end; a++, b++) if (toupper(*a) != toupper(*b)) break; if (b == needle_end) return haystack; } haystack++; } return NULL; } static const char* ImAtoi(const char* src, int* output) { int negative = 0; if (*src == '-') { negative = 1; src++; } if (*src == '+') { src++; } int v = 0; while (*src >= '0' && *src <= '9') v = (v * 10) + (*src++ - '0'); *output = negative ? -v : v; return src; } // A) 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. // B) When buf==NULL vsnprintf() will return the output size. #ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) { va_list args; va_start(args, fmt); int w = vsnprintf(buf, buf_size, fmt, args); va_end(args); if (buf == NULL) return w; if (w == -1 || w >= (int)buf_size) w = (int)buf_size - 1; buf[w] = 0; return w; } int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) { int w = vsnprintf(buf, buf_size, fmt, args); if (buf == NULL) return w; if (w == -1 || w >= (int)buf_size) w = (int)buf_size - 1; buf[w] = 0; return w; } #endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // 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; } } seed = ~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++]; } else { // Zero-terminated string while (unsigned char c = *current++) { // 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. // - 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; } //----------------------------------------------------------------------------- // ImText* helpers //----------------------------------------------------------------------------- // 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) { 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; } int ImTextStrFromUtf8(ImWchar* buf, int 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 (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; 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) { ImGuiStyle& style = GImGui->Style; ImVec4 c = style.Colors[idx]; c.w *= style.Alpha * alpha_mul; return ColorConvertFloat4ToU32(c); } ImU32 ImGui::GetColorU32(const ImVec4& col) { ImGuiStyle& style = GImGui->Style; ImVec4 c = col; c.w *= style.Alpha; return ColorConvertFloat4ToU32(c); } const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx) { ImGuiStyle& style = GImGui->Style; return style.Colors[idx]; } ImU32 ImGui::GetColorU32(ImU32 col) { float style_alpha = GImGui->Style.Alpha; if (style_alpha >= 1.0f) return col; int a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; a = (int)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); } // 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) { float K = 0.f; if (g < b) { ImSwap(g, b); K = -1.f; } if (r < g) { ImSwap(r, g); K = -2.f / 6.f - K; } const float chroma = r - (g < b ? g : b); out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f)); out_s = chroma / (r + 1e-20f); out_v = r; } // 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 out_r = out_g = out_b = v; return; } h = fmodf(h, 1.0f) / (60.0f/360.0f); int i = (int)h; float f = h - (float)i; float p = v * (1.0f - s); float q = v * (1.0f - s * f); float t = v * (1.0f - s * (1.0f - f)); switch (i) { case 0: out_r = v; out_g = t; out_b = p; break; case 1: out_r = q; out_g = v; out_b = p; break; case 2: out_r = p; out_g = v; out_b = t; break; case 3: out_r = p; out_g = q; out_b = v; break; case 4: out_r = t; out_g = p; out_b = v; break; case 5: default: out_r = v; out_g = p; out_b = q; break; } } FILE* ImFileOpen(const char* filename, const char* mode) { #if defined(_WIN32) && !defined(__CYGWIN__) // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can) const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1; const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1; ImVector buf; buf.resize(filename_wsize + mode_wsize); ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL); ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL); return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]); #else return fopen(filename, mode); #endif } // Load file content into memory // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes) { IM_ASSERT(filename && file_open_mode); if (out_file_size) *out_file_size = 0; FILE* f; if ((f = ImFileOpen(filename, file_open_mode)) == NULL) 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 NULL; } int file_size = (int)file_size_signed; void* file_data = ImGui::MemAlloc(file_size + padding_bytes); if (file_data == NULL) { fclose(f); return NULL; } if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size) { fclose(f); ImGui::MemFree(file_data); return NULL; } if (padding_bytes > 0) memset((void *)(((char*)file_data) + file_size), 0, padding_bytes); fclose(f); if (out_file_size) *out_file_size = file_size; return file_data; } //----------------------------------------------------------------------------- // ImGuiStorage // Helper: Key->value storage //----------------------------------------------------------------------------- // std::lower_bound but without the bullshit static ImVector::iterator LowerBound(ImVector& data, ImGuiID key) { ImVector::iterator first = data.begin(); ImVector::iterator last = data.end(); size_t count = (size_t)(last - first); while (count > 0) { size_t count2 = count >> 1; ImVector::iterator mid = first + count2; if (mid->key < key) { first = ++mid; count -= count2 + 1; } else { count = count2; } } return first; } // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. void ImGuiStorage::BuildSortByKey() { struct StaticFunc { static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs) { // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that. if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1; if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1; return 0; } }; if (Data.Size > 1) qsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID); } int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { ImVector::iterator it = LowerBound(const_cast&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_i; } bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const { return GetInt(key, default_val ? 1 : 0) != 0; } float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { ImVector::iterator it = LowerBound(const_cast&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_f; } void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { ImVector::iterator it = LowerBound(const_cast&>(Data), key); if (it == Data.end() || it->key != key) return NULL; return it->val_p; } // 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. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) { ImVector::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, 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::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_f; } void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { ImVector::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::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_i = val; } void ImGuiStorage::SetBool(ImGuiID key, bool val) { SetInt(key, val ? 1 : 0); } void ImGuiStorage::SetFloat(ImGuiID key, float val) { ImVector::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_f = val; } void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { ImVector::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_p = val; } void ImGuiStorage::SetAllInt(int v) { 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]" ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) { if (default_filter) { ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); Build(); } else { InputBuf[0] = 0; CountGrep = 0; } } bool ImGuiTextFilter::Draw(const char* label, float width) { if (width != 0.0f) ImGui::PushItemWidth(width); bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); if (width != 0.0f) ImGui::PopItemWidth(); if (value_changed) Build(); return value_changed; } void ImGuiTextFilter::TextRange::split(char separator, ImVector& out) { out.resize(0); const char* wb = b; const char* we = wb; while (we < e) { if (*we == separator) { out.push_back(TextRange(wb, we)); wb = we + 1; } we++; } if (wb != we) out.push_back(TextRange(wb, we)); } void ImGuiTextFilter::Build() { Filters.resize(0); TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); input_range.split(',', Filters); CountGrep = 0; for (int i = 0; i != Filters.Size; i++) { Filters[i].trim_blanks(); if (Filters[i].empty()) continue; if (Filters[i].front() != '-') CountGrep += 1; } } bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { if (Filters.empty()) return true; if (text == NULL) text = ""; for (int i = 0; i != Filters.Size; i++) { const TextRange& f = Filters[i]; if (f.empty()) continue; if (f.front() == '-') { // Subtract if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) return false; } else { // Grep if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) return true; } } // Implicit * grep if (CountGrep == 0) return true; return false; } //----------------------------------------------------------------------------- // ImGuiTextBuffer //----------------------------------------------------------------------------- // 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) #endif // Helper: Text buffer for logging/accumulating text void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) { va_list args_copy; va_copy(args_copy, args); int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. if (len <= 0) return; const int write_off = Buf.Size; const int needed_sz = write_off + len; if (write_off + len >= Buf.Capacity) { 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], len + 1, fmt, args_copy); } void ImGuiTextBuffer::appendf(const char* fmt, ...) { va_list args; va_start(args, fmt); appendfv(fmt, args); va_end(args); } //----------------------------------------------------------------------------- // ImGuiSimpleColumns (internal use only) //----------------------------------------------------------------------------- ImGuiMenuColumns::ImGuiMenuColumns() { Count = 0; Spacing = Width = NextWidth = 0.0f; memset(Pos, 0, sizeof(Pos)); memset(NextWidths, 0, sizeof(NextWidths)); } void ImGuiMenuColumns::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 ImGuiMenuColumns::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 ImGuiMenuColumns::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.ColumnsSet) window->DC.ColumnsSet->CellMinY = 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(ImGuiContext* context, const char* name) { Name = ImStrdup(name); ID = ImHash(name, 0); IDStack.push_back(ID); Flags = 0; PosFloat = Pos = ImVec2(0.0f, 0.0f); Size = SizeFull = ImVec2(0.0f, 0.0f); SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f); WindowPadding = ImVec2(0.0f, 0.0f); WindowRounding = 0.0f; WindowBorderSize = 0.0f; MoveId = GetID("#MOVE"); ChildId = 0; 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); Active = WasActive = false; WriteAccessed = false; Collapsed = false; CollapseToggleWanted = false; SkipItems = false; Appearing = false; CloseButton = false; BeginOrderWithinParent = -1; BeginOrderWithinContext = -1; BeginCount = 0; PopupId = 0; AutoFitFramesX = AutoFitFramesY = -1; AutoFitOnlyGrows = false; AutoFitChildAxises = 0x00; AutoPosLastDirection = ImGuiDir_None; HiddenFrames = 0; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); LastFrameActive = -1; ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; DrawList = IM_NEW(ImDrawList)(&context->DrawListSharedData); DrawList->_OwnerName = Name; ParentWindow = NULL; RootWindow = NULL; RootWindowForTitleBarHighlight = NULL; RootWindowForTabbing = NULL; RootWindowForNav = NULL; NavLastIds[0] = NavLastIds[1] = 0; NavRectRel[0] = NavRectRel[1] = ImRect(); NavLastChildNavWindow = NULL; FocusIdxAllCounter = FocusIdxTabCounter = -1; FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX; FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX; } ImGuiWindow::~ImGuiWindow() { IM_DELETE(DrawList); IM_DELETE(Name); for (int i = 0; i != ColumnsStorage.Size; i++) ColumnsStorage[i].~ImGuiColumnsSet(); } ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); 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(); ImGuiID id = ImHash(&ptr, sizeof(void*), seed); ImGui::KeepAliveID(id); return id; } 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); } // This is only used in rare/specific situations to manufacture an ID out of nowhere. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs) { ImGuiID seed = IDStack.back(); const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) }; ImGuiID id = ImHash(&r_rel, sizeof(r_rel), seed); ImGui::KeepAliveID(id); return id; } //----------------------------------------------------------------------------- // Internal API exposed in imgui_internal.h //----------------------------------------------------------------------------- static void SetCurrentWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.CurrentWindow = window; if (window) g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } static void SetNavID(ImGuiID id, int nav_layer) { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindow); IM_ASSERT(nav_layer == 0 || nav_layer == 1); g.NavId = id; g.NavWindow->NavLastIds[nav_layer] = id; } static void SetNavIDAndMoveMouse(ImGuiID id, int nav_layer, const ImRect& rect_rel) { ImGuiContext& g = *GImGui; SetNavID(id, nav_layer); g.NavWindow->NavRectRel[nav_layer] = rect_rel; g.NavMousePosDirty = true; g.NavDisableHighlight = false; g.NavDisableMouseHover = true; } void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.ActiveIdIsJustActivated = (g.ActiveId != id); if (g.ActiveIdIsJustActivated) g.ActiveIdTimer = 0.0f; g.ActiveId = id; g.ActiveIdAllowNavDirFlags = 0; g.ActiveIdAllowOverlap = false; g.ActiveIdWindow = window; if (id) { g.ActiveIdIsAlive = true; g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse; } } ImGuiID ImGui::GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window) { ImGuiContext& g = *GImGui; IM_ASSERT(id != 0); // Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it. const int nav_layer = window->DC.NavLayerCurrent; if (g.NavWindow != window) g.NavInitRequest = false; g.NavId = id; g.NavWindow = window; g.NavLayer = nav_layer; window->NavLastIds[nav_layer] = id; if (window->DC.LastItemId == id) window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos); if (g.ActiveIdSource == ImGuiInputSource_Nav) g.NavDisableMouseHover = true; else g.NavDisableHighlight = true; } void ImGui::ClearActiveID() { SetActiveID(0, NULL); } void ImGui::SetHoveredID(ImGuiID id) { ImGuiContext& g = *GImGui; g.HoveredId = id; g.HoveredIdAllowOverlap = false; g.HoveredIdTimer = (id != 0 && g.HoveredIdPreviousFrame == id) ? (g.HoveredIdTimer + g.IO.DeltaTime) : 0.0f; } ImGuiID ImGui::GetHoveredID() { ImGuiContext& g = *GImGui; return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame; } void ImGui::KeepAliveID(ImGuiID id) { ImGuiContext& g = *GImGui; if (g.ActiveId == id) g.ActiveIdIsAlive = true; } static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags) { // An active popup disable hovering on other windows (apart from its own children) // FIXME-OPT: This could be cached/stored within the window. ImGuiContext& g = *GImGui; if (g.NavWindow) if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow) if (focused_root_window->WasActive && focused_root_window != window->RootWindow) { // For the purpose of those flags we differentiate "standard popup" from "modal popup" // NB: The order of those two tests is important because Modal windows are also Popups. if (focused_root_window->Flags & ImGuiWindowFlags_Modal) return false; if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup)) return false; } return true; } // Advance cursor given item size for layout. void ImGui::ItemSize(const ImVec2& size, float text_offset_y) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; 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); //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG] 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 - g.Style.ItemSpacing.y); //if (g.IO.KeyAlt) 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; // Horizontal layout mode if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) SameLine(); } void ImGui::ItemSize(const ImRect& bb, float text_offset_y) { ItemSize(bb.GetSize(), text_offset_y); } static ImGuiDir NavScoreItemGetQuadrant(float dx, float dy) { if (fabsf(dx) > fabsf(dy)) return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left; return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up; } static float NavScoreItemDistInterval(float a0, float a1, float b0, float b1) { if (a1 < b0) return a1 - b0; if (b1 < a0) return a0 - b1; return 0.0f; } // Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057 static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavLayer != window->DC.NavLayerCurrent) return false; const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width) g.NavScoringCount++; // We perform scoring on items bounding box clipped by their parent window on the other axis (clipping on our movement axis would give us equal scores for all clipped items) if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) { cand.Min.y = ImClamp(cand.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y); cand.Max.y = ImClamp(cand.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y); } else { cand.Min.x = ImClamp(cand.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x); cand.Max.x = ImClamp(cand.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x); } // Compute distance between boxes // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed. float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x); float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items if (dby != 0.0f && dbx != 0.0f) dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f); float dist_box = fabsf(dbx) + fabsf(dby); // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x); float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y); float dist_center = fabsf(dcx) + fabsf(dcy); // L1 metric (need this for our connectedness guarantee) // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance ImGuiDir quadrant; float dax = 0.0f, day = 0.0f, dist_axial = 0.0f; if (dbx != 0.0f || dby != 0.0f) { // For non-overlapping boxes, use distance between boxes dax = dbx; day = dby; dist_axial = dist_box; quadrant = NavScoreItemGetQuadrant(dbx, dby); } else if (dcx != 0.0f || dcy != 0.0f) { // For overlapping boxes with different centers, use distance between centers dax = dcx; day = dcy; dist_axial = dist_center; quadrant = NavScoreItemGetQuadrant(dcx, dcy); } else { // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter) quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right; } #if IMGUI_DEBUG_NAV_SCORING char buf[128]; if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max)) { ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]); g.OverlayDrawList.AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100)); g.OverlayDrawList.AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200)); g.OverlayDrawList.AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150)); g.OverlayDrawList.AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf); } else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate. { if (IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; } if (quadrant == g.NavMoveDir) { ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center); g.OverlayDrawList.AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200)); g.OverlayDrawList.AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf); } } #endif // Is it in the quadrant we're interesting in moving to? bool new_best = false; if (quadrant == g.NavMoveDir) { // Does it beat the current best candidate? if (dist_box < result->DistBox) { result->DistBox = dist_box; result->DistCenter = dist_center; return true; } if (dist_box == result->DistBox) { // Try using distance between center points to break ties if (dist_center < result->DistCenter) { result->DistCenter = dist_center; new_best = true; } else if (dist_center == result->DistCenter) { // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index), // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis. if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance new_best = true; } } } // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness) // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too. // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward. // Disabling it may however lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option? if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f)) { result->DistAxial = dist_axial; new_best = true; } return new_best; } static void NavSaveLastChildNavWindow(ImGuiWindow* child_window) { ImGuiWindow* parent_window = child_window; while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) parent_window = parent_window->ParentWindow; if (parent_window && parent_window != child_window) parent_window->NavLastChildNavWindow = child_window; } // Call when we are expected to land on Layer 0 after FocusWindow() static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window) { return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window; } static void NavRestoreLayer(int layer) { ImGuiContext& g = *GImGui; g.NavLayer = layer; if (layer == 0) g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow); if (layer == 0 && g.NavWindow->NavLastIds[0] != 0) SetNavIDAndMoveMouse(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]); else ImGui::NavInitWindow(g.NavWindow, true); } static inline void NavUpdateAnyRequestFlag() { ImGuiContext& g = *GImGui; g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || IMGUI_DEBUG_NAV_SCORING; } static bool NavMoveRequestButNoResultYet() { ImGuiContext& g = *GImGui; return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0; } static void NavMoveRequestCancel() { ImGuiContext& g = *GImGui; g.NavMoveRequest = false; NavUpdateAnyRequestFlag(); } // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above) static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id) { ImGuiContext& g = *GImGui; //if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag. // return; const ImGuiItemFlags item_flags = window->DC.ItemFlags; const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos); if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent) { // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0) { g.NavInitResultId = id; g.NavInitResultRectRel = nav_bb_rel; } if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus)) { g.NavInitRequest = false; // Found a match, clear request NavUpdateAnyRequestFlag(); } } // Scoring for navigation if (g.NavId != id && !(item_flags & ImGuiItemFlags_NoNav)) { ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; #if IMGUI_DEBUG_NAV_SCORING // [DEBUG] Score all items in NavWindow at all times if (!g.NavMoveRequest) g.NavMoveDir = g.NavMoveDirLast; bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest; #else bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb); #endif if (new_best) { result->ID = id; result->ParentID = window->IDStack.back(); result->Window = window; result->RectRel = nav_bb_rel; } } // Update window-relative bounding box of navigated item if (g.NavId == id) { g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window. g.NavLayer = window->DC.NavLayerCurrent; g.NavIdIsAlive = true; g.NavIdTabCounter = window->FocusIdxTabCounter; window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position) } } // 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 // declare 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, ImGuiID id, const ImRect* nav_bb_arg) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (id != 0) { // Navigation processing runs prior to clipping early-out // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window. // it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick) window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask; if (g.NavId == id || g.NavAnyRequest) if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened)) NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id); } window->DC.LastItemId = id; window->DC.LastItemRect = bb; window->DC.LastItemStatusFlags = 0; // Clipping test const bool is_clipped = IsClippedEx(bb, id, false); if (is_clipped) return false; //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG] // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them) if (IsMouseHoveringRect(bb.Min, bb.Max)) window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect; return true; } // This is roughly matching the behavior of internal-facing ItemHoverable() // - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavDisableMouseHover && !g.NavDisableHighlight) return IsItemFocused(); // Test for bounding box overlap, as updated as ItemAdd() if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) return false; IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function // Test if we are hovering the right window (our window could be behind another window) // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself. // Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while. //if (g.HoveredWindow != window) // return false; if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped)) return false; // Test if another item is active (e.g. being dragged) if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId) return false; // Test if interactions on this window are blocked by an active popup or modal if (!IsWindowContentHoverable(window, flags)) return false; // Test if the item is disabled if (window->DC.ItemFlags & ImGuiItemFlags_Disabled) return false; // Special handling for the 1st item after Begin() which represent the title bar. When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect tht case. if (window->DC.LastItemId == window->MoveId && window->WriteAccessed) return false; return true; } // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered(). bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) { ImGuiContext& g = *GImGui; if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap) return false; ImGuiWindow* window = g.CurrentWindow; if (g.HoveredWindow != window) return false; if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) return false; if (!IsMouseHoveringRect(bb.Min, bb.Max)) return false; if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_Default)) return false; if (window->DC.ItemFlags & ImGuiItemFlags_Disabled) return false; SetHoveredID(id); return true; } bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!bb.Overlaps(window->ClipRect)) if (id == 0 || id != g.ActiveId) if (clip_even_when_logged || !g.LogEnabled) return true; return false; } bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop) { ImGuiContext& g = *GImGui; const bool allow_keyboard_focus = (window->DC.ItemFlags & (ImGuiItemFlags_AllowKeyboardFocus | ImGuiItemFlags_Disabled)) == ImGuiItemFlags_AllowKeyboardFocus; window->FocusIdxAllCounter++; if (allow_keyboard_focus) window->FocusIdxTabCounter++; // Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item. // Note that we can always TAB out of a widget that doesn't allow tabbing in. if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab)) window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items. if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent) return true; if (allow_keyboard_focus && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent) { g.NavJustTabbedId = id; return true; } return false; } void ImGui::FocusableItemUnregister(ImGuiWindow* window) { window->FocusIdxAllCounter--; window->FocusIdxTabCounter--; } ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y) { 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; } float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { 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) { GImAllocatorActiveAllocationsCount++; return GImAllocatorAllocFunc(sz, GImAllocatorUserData); } void ImGui::MemFree(void* ptr) { if (ptr) GImAllocatorActiveAllocationsCount--; return GImAllocatorFreeFunc(ptr, GImAllocatorUserData); } const char* ImGui::GetClipboardText() { return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : ""; } void ImGui::SetClipboardText(const char* text) { if (GImGui->IO.SetClipboardTextFn) GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text); } const char* ImGui::GetVersion() { return IMGUI_VERSION; } // 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; } void ImGui::SetCurrentContext(ImGuiContext* ctx) { #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this. #else GImGui = ctx; #endif } void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data) { GImAllocatorAllocFunc = alloc_func; GImAllocatorFreeFunc = free_func; GImAllocatorUserData = user_data; } ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas) { ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas); if (GImGui == NULL) SetCurrentContext(ctx); return ctx; } void ImGui::DestroyContext(ImGuiContext* ctx) { if (ctx == NULL) ctx = GImGui; Shutdown(ctx); if (GImGui == ctx) SetCurrentContext(NULL); IM_DELETE(ctx); } ImGuiIO& ImGui::GetIO() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?"); return GImGui->IO; } ImGuiStyle& ImGui::GetStyle() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?"); return GImGui->Style; } // Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame() ImDrawData* ImGui::GetDrawData() { return GImGui->DrawData.Valid ? &GImGui->DrawData : NULL; } float ImGui::GetTime() { return GImGui->Time; } int ImGui::GetFrameCount() { return GImGui->FrameCount; } ImDrawList* ImGui::GetOverlayDrawList() { return &GImGui->OverlayDrawList; } ImDrawListSharedData* ImGui::GetDrawListSharedData() { return &GImGui->DrawListSharedData; } // This needs to be called before we submit any widget (aka in or before Begin) void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit) { ImGuiContext& g = *GImGui; IM_ASSERT(window == g.NavWindow); bool init_for_nav = false; if (!(window->Flags & ImGuiWindowFlags_NoNavInputs)) if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit) init_for_nav = true; if (init_for_nav) { SetNavID(0, g.NavLayer); g.NavInitRequest = true; g.NavInitRequestFromMove = false; g.NavInitResultId = 0; g.NavInitResultRectRel = ImRect(); NavUpdateAnyRequestFlag(); } else { g.NavId = window->NavLastIds[0]; } } static ImVec2 NavCalcPreferredMousePos() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.NavWindow; if (!window) return g.IO.MousePos; const ImRect& rect_rel = window->NavRectRel[g.NavLayer]; ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x*4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight())); ImRect visible_rect = GetViewportRect(); return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta. } static int FindWindowIndex(ImGuiWindow* window) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; for (int i = g.Windows.Size-1; i >= 0; i--) if (g.Windows[i] == window) return i; return -1; } static ImGuiWindow* FindWindowNavigable(int i_start, int i_stop, int dir) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; for (int i = i_start; i >= 0 && i < g.Windows.Size && i != i_stop; i += dir) if (ImGui::IsWindowNavFocusable(g.Windows[i])) return g.Windows[i]; return NULL; } float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode) { ImGuiContext& g = *GImGui; if (mode == ImGuiInputReadMode_Down) return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user) const float t = g.IO.NavInputsDownDuration[n]; if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input. return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f); if (t < 0.0f) return 0.0f; if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input. return (t == 0.0f) ? 1.0f : 0.0f; if (mode == ImGuiInputReadMode_Repeat) return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f); if (mode == ImGuiInputReadMode_RepeatSlow) return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f); if (mode == ImGuiInputReadMode_RepeatFast) return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f); return 0.0f; } // Equivalent of IsKeyDown() for NavInputs[] static bool IsNavInputDown(ImGuiNavInput n) { return GImGui->IO.NavInputs[n] > 0.0f; } // Equivalent of IsKeyPressed() for NavInputs[] static bool IsNavInputPressed(ImGuiNavInput n, ImGuiInputReadMode mode) { return ImGui::GetNavInputAmount(n, mode) > 0.0f; } static bool IsNavInputPressedAnyOfTwo(ImGuiNavInput n1, ImGuiNavInput n2, ImGuiInputReadMode mode) { return (ImGui::GetNavInputAmount(n1, mode) + ImGui::GetNavInputAmount(n2, mode)) > 0.0f; } ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor) { ImVec2 delta(0.0f, 0.0f); if (dir_sources & ImGuiNavDirSourceFlags_Keyboard) delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode)); if (dir_sources & ImGuiNavDirSourceFlags_PadDPad) delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode)); if (dir_sources & ImGuiNavDirSourceFlags_PadLStick) delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode)); if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow)) delta *= slow_factor; if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast)) delta *= fast_factor; return delta; } static void NavUpdateWindowingHighlightWindow(int focus_change_dir) { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindowingTarget); if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal) return; const int i_current = FindWindowIndex(g.NavWindowingTarget); ImGuiWindow* window_target = FindWindowNavigable(i_current + focus_change_dir, -INT_MAX, focus_change_dir); if (!window_target) window_target = FindWindowNavigable((focus_change_dir < 0) ? (g.Windows.Size - 1) : 0, i_current, focus_change_dir); g.NavWindowingTarget = window_target; g.NavWindowingToggleLayer = false; } // Window management mode (hold to: change focus/move/resize, tap to: toggle menu layer) static void ImGui::NavUpdateWindowing() { ImGuiContext& g = *GImGui; ImGuiWindow* apply_focus_window = NULL; bool apply_toggle_layer = false; bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed); bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.NavFlags & ImGuiNavFlags_EnableKeyboard); if (start_windowing_with_gamepad || start_windowing_with_keyboard) if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavigable(g.Windows.Size - 1, -INT_MAX, -1)) { g.NavWindowingTarget = window->RootWindowForTabbing; g.NavWindowingHighlightTimer = g.NavWindowingHighlightAlpha = 0.0f; g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true; g.NavWindowingInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad; } // Gamepad update g.NavWindowingHighlightTimer += g.IO.DeltaTime; if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_NavGamepad) { // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingHighlightTimer - 0.20f) / 0.05f)); // Select window to focus const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow); if (focus_change_dir != 0) { NavUpdateWindowingHighlightWindow(focus_change_dir); g.NavWindowingHighlightAlpha = 1.0f; } // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most) if (!IsNavInputDown(ImGuiNavInput_Menu)) { g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. if (g.NavWindowingToggleLayer && g.NavWindow) apply_toggle_layer = true; else if (!g.NavWindowingToggleLayer) apply_focus_window = g.NavWindowingTarget; g.NavWindowingTarget = NULL; } } // Keyboard: Focus if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_NavKeyboard) { // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingHighlightTimer - 0.15f) / 0.04f)); // 1.0f if (IsKeyPressedMap(ImGuiKey_Tab, true)) NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1); if (!g.IO.KeyCtrl) apply_focus_window = g.NavWindowingTarget; } // Keyboard: Press and Release ALT to toggle menu layer // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released)) if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev)) apply_toggle_layer = true; // Move window if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove)) { ImVec2 move_delta; if (g.NavWindowingInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift) move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down); if (g.NavWindowingInputSource == ImGuiInputSource_NavGamepad) move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down); if (move_delta.x != 0.0f || move_delta.y != 0.0f) { const float NAV_MOVE_SPEED = 800.0f; const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); g.NavWindowingTarget->PosFloat += move_delta * move_speed; g.NavDisableMouseHover = true; MarkIniSettingsDirty(g.NavWindowingTarget); } } // Apply final focus if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindowForTabbing)) { g.NavDisableHighlight = false; g.NavDisableMouseHover = true; apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window); ClosePopupsOverWindow(apply_focus_window); FocusWindow(apply_focus_window); if (apply_focus_window->NavLastIds[0] == 0) NavInitWindow(apply_focus_window, false); // If the window only has a menu layer, select it directly if (apply_focus_window->DC.NavLayerActiveMask == (1 << 1)) g.NavLayer = 1; } if (apply_focus_window) g.NavWindowingTarget = NULL; // Apply menu/layer toggle if (apply_toggle_layer && g.NavWindow) { ImGuiWindow* new_nav_window = g.NavWindow; while ((new_nav_window->DC.NavLayerActiveMask & (1 << 1)) == 0 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) new_nav_window = new_nav_window->ParentWindow; if (new_nav_window != g.NavWindow) { ImGuiWindow* old_nav_window = g.NavWindow; FocusWindow(new_nav_window); new_nav_window->NavLastChildNavWindow = old_nav_window; } g.NavDisableHighlight = false; g.NavDisableMouseHover = true; NavRestoreLayer((g.NavWindow->DC.NavLayerActiveMask & (1 << 1)) ? (g.NavLayer ^ 1) : 0); } } // NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated. static void NavScrollToBringItemIntoView(ImGuiWindow* window, ImRect& item_rect_rel) { // Scroll to keep newly navigated item fully into view ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1)); //g.OverlayDrawList.AddRect(window->Pos + window_rect_rel.Min, window->Pos + window_rect_rel.Max, IM_COL32_WHITE); // [DEBUG] if (window_rect_rel.Contains(item_rect_rel)) return; ImGuiContext& g = *GImGui; if (window->ScrollbarX && item_rect_rel.Min.x < window_rect_rel.Min.x) { window->ScrollTarget.x = item_rect_rel.Min.x + window->Scroll.x - g.Style.ItemSpacing.x; window->ScrollTargetCenterRatio.x = 0.0f; } else if (window->ScrollbarX && item_rect_rel.Max.x >= window_rect_rel.Max.x) { window->ScrollTarget.x = item_rect_rel.Max.x + window->Scroll.x + g.Style.ItemSpacing.x; window->ScrollTargetCenterRatio.x = 1.0f; } if (item_rect_rel.Min.y < window_rect_rel.Min.y) { window->ScrollTarget.y = item_rect_rel.Min.y + window->Scroll.y - g.Style.ItemSpacing.y; window->ScrollTargetCenterRatio.y = 0.0f; } else if (item_rect_rel.Max.y >= window_rect_rel.Max.y) { window->ScrollTarget.y = item_rect_rel.Max.y + window->Scroll.y + g.Style.ItemSpacing.y; window->ScrollTargetCenterRatio.y = 1.0f; } // Estimate upcoming scroll so we can offset our relative mouse position so mouse position can be applied immediately (under this block) ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window); item_rect_rel.Translate(window->Scroll - next_scroll); } static void ImGui::NavUpdate() { ImGuiContext& g = *GImGui; g.IO.WantMoveMouse = false; #if 0 if (g.NavScoringCount > 0) printf("[%05d] NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest); #endif // Update Keyboard->Nav inputs mapping memset(g.IO.NavInputs + ImGuiNavInput_InternalStart_, 0, (ImGuiNavInput_COUNT - ImGuiNavInput_InternalStart_) * sizeof(g.IO.NavInputs[0])); if (g.IO.NavFlags & ImGuiNavFlags_EnableKeyboard) { #define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (g.IO.KeyMap[_KEY] != -1 && IsKeyDown(g.IO.KeyMap[_KEY])) g.IO.NavInputs[_NAV_INPUT] = 1.0f; NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate ); NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input ); NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel ); NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ ); NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_); NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ ); NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ ); if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f; if (g.IO.KeyAlt) g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f; #undef NAV_MAP_KEY } memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration)); for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++) g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f; // Process navigation init request (select first/default focus) if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove)) { // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) IM_ASSERT(g.NavWindow); if (g.NavInitRequestFromMove) SetNavIDAndMoveMouse(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel); else SetNavID(g.NavInitResultId, g.NavLayer); g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel; } g.NavInitRequest = false; g.NavInitRequestFromMove = false; g.NavInitResultId = 0; g.NavJustMovedToId = 0; // Process navigation move request if (g.NavMoveRequest && (g.NavMoveResultLocal.ID != 0 || g.NavMoveResultOther.ID != 0)) { // Select which result to use ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; if (g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow) // Maybe entering a flattened child? In this case solve the tie using the regular scoring rules if ((g.NavMoveResultOther.DistBox < g.NavMoveResultLocal.DistBox) || (g.NavMoveResultOther.DistBox == g.NavMoveResultLocal.DistBox && g.NavMoveResultOther.DistCenter < g.NavMoveResultLocal.DistCenter)) result = &g.NavMoveResultOther; IM_ASSERT(g.NavWindow && result->Window); // Scroll to keep newly navigated item fully into view if (g.NavLayer == 0) NavScrollToBringItemIntoView(result->Window, result->RectRel); // Apply result from previous frame navigation directional move request ClearActiveID(); g.NavWindow = result->Window; SetNavIDAndMoveMouse(result->ID, g.NavLayer, result->RectRel); g.NavJustMovedToId = result->ID; g.NavMoveFromClampedRefRect = false; } // When a forwarded move request failed, we restore the highlight that we disabled during the forward frame if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive) { IM_ASSERT(g.NavMoveRequest); if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0) g.NavDisableHighlight = false; g.NavMoveRequestForward = ImGuiNavForward_None; } // Apply application mouse position movement, after we had a chance to process move request result. if (g.NavMousePosDirty && g.NavIdIsAlive) { // Set mouse position given our knowledge of the nav widget position from last frame if (g.IO.NavFlags & ImGuiNavFlags_MoveMouse) { g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredMousePos(); g.IO.WantMoveMouse = true; } g.NavMousePosDirty = false; } g.NavIdIsAlive = false; g.NavJustTabbedId = 0; IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1); // Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0 if (g.NavWindow) NavSaveLastChildNavWindow(g.NavWindow); if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0) g.NavWindow->NavLastChildNavWindow = NULL; NavUpdateWindowing(); // Set output flags for user application g.IO.NavActive = (g.IO.NavFlags & (ImGuiNavFlags_EnableGamepad | ImGuiNavFlags_EnableKeyboard)) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs); g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL) || g.NavInitRequest; // Process NavCancel input (to close a popup, get back to parent, clear focus) if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed)) { if (g.ActiveId != 0) { ClearActiveID(); } else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow) { // Exit child window ImGuiWindow* child_window = g.NavWindow; ImGuiWindow* parent_window = g.NavWindow->ParentWindow; IM_ASSERT(child_window->ChildId != 0); FocusWindow(parent_window); SetNavID(child_window->ChildId, 0); g.NavIdIsAlive = false; if (g.NavDisableMouseHover) g.NavMousePosDirty = true; } else if (g.OpenPopupStack.Size > 0) { // Close open popup/menu if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal)) ClosePopupToLevel(g.OpenPopupStack.Size - 1); } else if (g.NavLayer != 0) { // Leave the "menu" layer NavRestoreLayer(0); } else { // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow))) g.NavWindow->NavLastIds[0] = 0; g.NavId = 0; } } // Process manual activation request g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0; if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) { bool activate_down = IsNavInputDown(ImGuiNavInput_Activate); bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed); if (g.ActiveId == 0 && activate_pressed) g.NavActivateId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down) g.NavActivateDownId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed) g.NavActivatePressedId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed)) g.NavInputId = g.NavId; } if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) g.NavDisableHighlight = true; if (g.NavActivateId != 0) IM_ASSERT(g.NavActivateDownId == g.NavActivateId); g.NavMoveRequest = false; // Process programmatic activation request if (g.NavNextActivateId != 0) g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId; g.NavNextActivateId = 0; // Initiate directional inputs request const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags; if (g.NavMoveRequestForward == ImGuiNavForward_None) { g.NavMoveDir = ImGuiDir_None; if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) { if ((allowed_dir_flags & (1<Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget) { // *Fallback* manual-scroll with NavUp/NavDown when window has no navigable item ImGuiWindow* window = g.NavWindow; const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported. if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest) { if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed)); if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed)); } // *Normal* Manual scroll with NavScrollXXX keys // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f); if (scroll_dir.x != 0.0f && window->ScrollbarX) { SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); g.NavMoveFromClampedRefRect = true; } if (scroll_dir.y != 0.0f) { SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed)); g.NavMoveFromClampedRefRect = true; } } // Reset search results g.NavMoveResultLocal.Clear(); g.NavMoveResultOther.Clear(); // When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0) { ImGuiWindow* window = g.NavWindow; ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1)); if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer])) { float pad = window->CalcFontSize() * 0.5f; window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel); g.NavId = 0; } g.NavMoveFromClampedRefRect = false; } // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) ImRect nav_rect_rel = (g.NavWindow && g.NavWindow->NavRectRel[g.NavLayer].IsFinite()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0); g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect(); g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x); g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x; IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous fabsf() calls in NavScoreItem(). //g.OverlayDrawList.AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG] g.NavScoringCount = 0; #if IMGUI_DEBUG_NAV_RECTS if (g.NavWindow) { for (int layer = 0; layer < 2; layer++) g.OverlayDrawList.AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG] if (g.NavWindow) { ImU32 col = (g.NavWindow->HiddenFrames <= 0) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredMousePos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); g.OverlayDrawList.AddCircleFilled(p, 3.0f, col); g.OverlayDrawList.AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); } #endif } static void ImGui::UpdateMovingWindow() { ImGuiContext& g = *GImGui; if (g.MovingWindow && g.MovingWindow->MoveId == g.ActiveId && g.ActiveIdSource == ImGuiInputSource_Mouse) { // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window). // We track it to preserve Focus and so that ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency. KeepAliveID(g.ActiveId); IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow); ImGuiWindow* moving_window = g.MovingWindow->RootWindow; if (g.IO.MouseDown[0]) { ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset; if (moving_window->PosFloat.x != pos.x || moving_window->PosFloat.y != pos.y) { MarkIniSettingsDirty(moving_window); moving_window->PosFloat = pos; } FocusWindow(g.MovingWindow); } else { ClearActiveID(); g.MovingWindow = NULL; } } else { // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others. if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId) { KeepAliveID(g.ActiveId); if (!g.IO.MouseDown[0]) ClearActiveID(); } g.MovingWindow = NULL; } } void ImGui::NewFrame() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?"); ImGuiContext& g = *GImGui; // Check user data // (We pass an error message in the assert expression as a trick to get it visible to programmers who are not using a debugger, as most assert handlers display their argument) 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 && "Invalid DisplaySize value"); IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting"); IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)"); IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); for (int n = 0; n < ImGuiKey_COUNT; n++) IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)"); // Do a simple check for required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was super recently added in 1.60 WIP) if (g.IO.NavFlags & ImGuiNavFlags_EnableKeyboard) IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation."); // Initialize on first frame if (!g.Initialized) Initialize(&g); g.Time += g.IO.DeltaTime; g.FrameCount += 1; g.TooltipOverrideCount = 0; g.WindowsActiveCount = 0; SetCurrentFont(GetDefaultFont()); IM_ASSERT(g.Font->IsLoaded()); g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; g.OverlayDrawList.Clear(); g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID); g.OverlayDrawList.PushClipRectFullScreen(); g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); // Mark rendering data as invalid to prevent user who may have a handle on it to use it g.DrawData.Clear(); // Clear reference to active widget if the widget isn't alive anymore if (!g.HoveredIdPreviousFrame) g.HoveredIdTimer = 0.0f; g.HoveredIdPreviousFrame = g.HoveredId; g.HoveredId = 0; g.HoveredIdAllowOverlap = false; if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) ClearActiveID(); if (g.ActiveId) g.ActiveIdTimer += g.IO.DeltaTime; g.ActiveIdPreviousFrame = g.ActiveId; g.ActiveIdIsAlive = false; g.ActiveIdIsJustActivated = false; if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId) g.ScalarAsInputTextId = 0; // Elapse drag & drop payload if (g.DragDropActive && g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) { ClearDragDrop(); g.DragDropPayloadBufHeap.clear(); memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); } g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr; g.DragDropAcceptIdCurr = 0; g.DragDropAcceptIdCurrRectSurface = FLT_MAX; // Update keyboard input state 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; // Update gamepad/keyboard directional navigation NavUpdate(); // Update mouse input state // If mouse just appeared or disappeared (usually denoted by -FLT_MAX component, but in reality we test for -256000.0f) we cancel out movement in MouseDelta if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev)) g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; else g.IO.MouseDelta = ImVec2(0.0f, 0.0f); if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f) g.NavDisableMouseHover = false; g.IO.MousePosPrev = g.IO.MousePos; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { 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]) { if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime) { if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) g.IO.MouseDoubleClicked[i] = true; g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click } else { g.IO.MouseClickedTime[i] = g.Time; } g.IO.MouseClickedPos[i] = g.IO.MousePos; g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f); g.IO.MouseDragMaxDistanceSqr[i] = 0.0f; } else if (g.IO.MouseDown[i]) { ImVec2 mouse_delta = g.IO.MousePos - g.IO.MouseClickedPos[i]; g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, mouse_delta.x < 0.0f ? -mouse_delta.x : mouse_delta.x); g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, mouse_delta.y < 0.0f ? -mouse_delta.y : mouse_delta.y); g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(mouse_delta)); } if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation g.NavDisableMouseHover = false; } // Calculate frame-rate for the user, as a purely luxurious feature g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame)); // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) UpdateMovingWindow(); // Delay saving settings so we don't spam disk too much if (g.SettingsDirtyTimer > 0.0f) { g.SettingsDirtyTimer -= g.IO.DeltaTime; if (g.SettingsDirtyTimer <= 0.0f) SaveIniSettingsToDisk(g.IO.IniFilename); } // Find the window we are hovering // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow. // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point. // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. g.HoveredWindow = (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoInputs)) ? g.MovingWindow : FindHoveredWindow(g.IO.MousePos); g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; ImGuiWindow* modal_window = GetFrontMostModalRootWindow(); if (modal_window != NULL) { g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f); if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) g.HoveredRootWindow = g.HoveredWindow = NULL; } else { g.ModalWindowDarkeningRatio = 0.0f; } // Update the WantCaptureMouse/WantCaptureKeyboard flags, so user 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. 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.OpenPopupStack.empty()); mouse_any_down |= g.IO.MouseDown[i]; if (g.IO.MouseDown[i]) if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down]) mouse_earliest_button_down = i; } bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down]; if (g.WantCaptureMouseNextFrame != -1) g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0); else g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty()); if (g.WantCaptureKeyboardNextFrame != -1) g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0); else g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL); if (g.IO.NavActive && (g.IO.NavFlags & ImGuiNavFlags_EnableKeyboard) && !(g.IO.NavFlags & ImGuiNavFlags_NoCaptureKeyboard)) g.IO.WantCaptureKeyboard = true; g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : 0; g.MouseCursor = ImGuiMouseCursor_Arrow; g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -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. // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0; if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload) g.HoveredWindow = g.HoveredRootWindow = NULL; // Mouse wheel scrolling, scale if (g.HoveredWindow && !g.HoveredWindow->Collapsed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f)) { // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set). ImGuiWindow* window = g.HoveredWindow; ImGuiWindow* scroll_window = window; while ((scroll_window->Flags & ImGuiWindowFlags_ChildWindow) && (scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoScrollbar) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs) && scroll_window->ParentWindow) scroll_window = scroll_window->ParentWindow; const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs); if (g.IO.MouseWheel != 0.0f) { if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling) { // Zoom / Scale window const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); const float scale = new_font_scale / window->FontWindowScale; window->FontWindowScale = new_font_scale; const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; window->Pos += offset; window->PosFloat += offset; window->Size *= scale; window->SizeFull *= scale; } else if (!g.IO.KeyCtrl && scroll_allowed) { // Mouse wheel vertical scrolling float scroll_amount = 5 * scroll_window->CalcFontSize(); scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f); SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount); } } if (g.IO.MouseWheelH != 0.0f && scroll_allowed) { // Mouse wheel horizontal scrolling (for hardware that supports it) float scroll_amount = scroll_window->CalcFontSize(); if (!g.IO.KeyCtrl && !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse)) SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheelH * scroll_amount); } } // Pressing TAB activate widget focus if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab, false)) { if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX) g.NavWindow->FocusIdxTabRequestNext = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1); else g.NavWindow->FocusIdxTabRequestNext = g.IO.KeyShift ? -1 : 0; } g.NavIdTabCounter = INT_MAX; // Mark all windows as not visible for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; window->WasActive = window->Active; window->Active = false; window->WriteAccessed = false; } // Closing the focused window restore focus to the first active root window in descending z-order if (g.NavWindow && !g.NavWindow->WasActive) FocusFrontMostActiveWindow(NULL); // 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); ClosePopupsOverWindow(g.NavWindow); // Create implicit window - we will only render it if the user has added something to it. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver); Begin("Debug##Default"); } static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHash(name, 0)); if (!settings) settings = AddWindowSettings(name); return (void*)settings; } static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) { ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; float x, y; int i; if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y); else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize); else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); } static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { // Gather data from windows that were active during this session ImGuiContext& g = *imgui_ctx; for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Flags & ImGuiWindowFlags_NoSavedSettings) continue; ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID); if (!settings) settings = AddWindowSettings(window->Name); settings->Pos = window->Pos; settings->Size = window->SizeFull; settings->Collapsed = window->Collapsed; } // Write a buffer // If a window wasn't opened in this session we preserve its settings buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve for (int i = 0; i != g.SettingsWindows.Size; i++) { const ImGuiWindowSettings* settings = &g.SettingsWindows[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; buf->appendf("[%s][%s]\n", handler->TypeName, name); buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); buf->appendf("Collapsed=%d\n", settings->Collapsed); buf->appendf("\n"); } } void ImGui::Initialize(ImGuiContext* context) { ImGuiContext& g = *context; g.LogClipboard = IM_NEW(ImGuiTextBuffer)(); // Add .ini handle for ImGuiWindow type ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Window"; ini_handler.TypeHash = ImHash("Window", 0, 0); ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen; ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine; ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll; g.SettingsHandlers.push_front(ini_handler); // Load .ini file IM_ASSERT(g.SettingsWindows.empty()); LoadIniSettingsFromDisk(g.IO.IniFilename); g.Initialized = true; } // This function is merely here to free heap allocations. void ImGui::Shutdown(ImGuiContext* context) { ImGuiContext& g = *context; // 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 && g.FontAtlasOwnedByContext) IM_DELETE(g.IO.Fonts); // Cleanup of other data are conditional on actually having initialize ImGui. if (!g.Initialized) return; SaveIniSettingsToDisk(g.IO.IniFilename); for (int i = 0; i < g.Windows.Size; i++) IM_DELETE(g.Windows[i]); g.Windows.clear(); g.WindowsSortBuffer.clear(); g.CurrentWindow = NULL; g.CurrentWindowStack.clear(); g.WindowsById.Clear(); g.NavWindow = NULL; g.HoveredWindow = NULL; g.HoveredRootWindow = NULL; g.ActiveIdWindow = NULL; g.MovingWindow = NULL; for (int i = 0; i < g.SettingsWindows.Size; i++) IM_DELETE(g.SettingsWindows[i].Name); g.ColorModifiers.clear(); g.StyleModifiers.clear(); g.FontStack.clear(); g.OpenPopupStack.clear(); g.CurrentPopupStack.clear(); g.DrawDataBuilder.ClearFreeMemory(); g.OverlayDrawList.ClearFreeMemory(); g.PrivateClipboard.clear(); g.InputTextState.Text.clear(); g.InputTextState.InitialText.clear(); g.InputTextState.TempTextBuffer.clear(); g.SettingsWindows.clear(); g.SettingsHandlers.clear(); if (g.LogFile && g.LogFile != stdout) { fclose(g.LogFile); g.LogFile = NULL; } if (g.LogClipboard) IM_DELETE(g.LogClipboard); g.Initialized = false; } ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id) { ImGuiContext& g = *GImGui; for (int i = 0; i != g.SettingsWindows.Size; i++) if (g.SettingsWindows[i].Id == id) return &g.SettingsWindows[i]; return NULL; } static ImGuiWindowSettings* AddWindowSettings(const char* name) { ImGuiContext& g = *GImGui; g.SettingsWindows.push_back(ImGuiWindowSettings()); ImGuiWindowSettings* settings = &g.SettingsWindows.back(); settings->Name = ImStrdup(name); settings->Id = ImHash(name, 0); return settings; } static void LoadIniSettingsFromDisk(const char* ini_filename) { if (!ini_filename) return; char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", NULL, +1); if (!file_data) return; LoadIniSettingsFromMemory(file_data); ImGui::MemFree(file_data); } ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) { ImGuiContext& g = *GImGui; const ImGuiID type_hash = ImHash(type_name, 0, 0); for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) if (g.SettingsHandlers[handler_n].TypeHash == type_hash) return &g.SettingsHandlers[handler_n]; return NULL; } // Zero-tolerance, no error reporting, cheap .ini parsing static void LoadIniSettingsFromMemory(const char* buf_readonly) { // For convenience and to make the code simpler, we'll write zero terminators inside the buffer. So let's create a writable copy. char* buf = ImStrdup(buf_readonly); char* buf_end = buf + strlen(buf); ImGuiContext& g = *GImGui; void* entry_data = NULL; ImGuiSettingsHandler* entry_handler = NULL; char* line_end = NULL; for (char* line = buf; line < buf_end; line = line_end + 1) { // Skip new lines markers, then find end of the line while (*line == '\n' || *line == '\r') line++; line_end = line; while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') line_end++; line_end[0] = 0; if (line[0] == '[' && line_end > line && line_end[-1] == ']') { // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. line_end[-1] = 0; const char* name_end = line_end - 1; const char* type_start = line + 1; char* type_end = ImStrchrRange(type_start, name_end, ']'); const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; if (!type_end || !name_start) { name_start = type_start; // Import legacy entries that have no type type_start = "Window"; } else { *type_end = 0; // Overwrite first ']' name_start++; // Skip second '[' } entry_handler = ImGui::FindSettingsHandler(type_start); entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL; } else if (entry_handler != NULL && entry_data != NULL) { // Let type handler parse the line entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); } } ImGui::MemFree(buf); } static void SaveIniSettingsToDisk(const char* ini_filename) { ImGuiContext& g = *GImGui; g.SettingsDirtyTimer = 0.0f; if (!ini_filename) return; ImVector buf; SaveIniSettingsToMemory(buf); FILE* f = ImFileOpen(ini_filename, "wt"); if (!f) return; fwrite(buf.Data, sizeof(char), (size_t)buf.Size, f); fclose(f); } static void SaveIniSettingsToMemory(ImVector& out_buf) { ImGuiContext& g = *GImGui; g.SettingsDirtyTimer = 0.0f; ImGuiTextBuffer buf; for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) { ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n]; handler->WriteAllFn(&g, handler, &buf); } buf.Buf.pop_back(); // Remove extra zero-terminator used by ImGuiTextBuffer out_buf.swap(buf.Buf); } void ImGui::MarkIniSettingsDirty() { ImGuiContext& g = *GImGui; if (g.SettingsDirtyTimer <= 0.0f) g.SettingsDirtyTimer = g.IO.IniSavingRate; } static void MarkIniSettingsDirty(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) if (g.SettingsDirtyTimer <= 0.0f) g.SettingsDirtyTimer = g.IO.IniSavingRate; } // FIXME: Add a more explicit sort order in the window structure. static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs) { const ImGuiWindow* a = *(const ImGuiWindow**)lhs; const ImGuiWindow* b = *(const ImGuiWindow**)rhs; if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) return d; if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) return d; return (a->BeginOrderWithinParent - b->BeginOrderWithinParent); } static void AddWindowToSortedBuffer(ImVector* out_sorted_windows, ImGuiWindow* window) { out_sorted_windows->push_back(window); if (window->Active) { int count = window->DC.ChildWindows.Size; if (count > 1) 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->Active) AddWindowToSortedBuffer(out_sorted_windows, child); } } } static void AddDrawListToDrawData(ImVector* out_render_list, ImDrawList* draw_list) { 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; } // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly. 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 = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window) // If this assert triggers because you are drawing lots of stuff manually: // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents. // B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes. // You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing: // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API. // C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists. if (sizeof(ImDrawIdx) == 2) IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above"); out_render_list->push_back(draw_list); } static void AddWindowToDrawData(ImVector* out_render_list, ImGuiWindow* window) { AddDrawListToDrawData(out_render_list, window->DrawList); for (int i = 0; i < window->DC.ChildWindows.Size; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (child->Active && child->HiddenFrames <= 0) // clipped children may have been marked not active AddWindowToDrawData(out_render_list, child); } } static void AddWindowToDrawDataSelectLayer(ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.IO.MetricsActiveWindows++; if (window->Flags & ImGuiWindowFlags_Tooltip) AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window); else AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window); } void ImDrawDataBuilder::FlattenIntoSingleLayer() { int n = Layers[0].Size; int size = n; for (int i = 1; i < IM_ARRAYSIZE(Layers); i++) size += Layers[i].Size; Layers[0].resize(size); for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++) { ImVector& layer = Layers[layer_n]; if (layer.empty()) continue; memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*)); n += layer.Size; layer.resize(0); } } static void SetupDrawData(ImVector* draw_lists, ImDrawData* out_draw_data) { out_draw_data->Valid = true; out_draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL; out_draw_data->CmdListsCount = draw_lists->Size; out_draw_data->TotalVtxCount = out_draw_data->TotalIdxCount = 0; for (int n = 0; n < draw_lists->Size; n++) { out_draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size; out_draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size; } } // 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(); } void ImGui::PopClipRect() { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PopClipRect(); window->ClipRect = window->DrawList->_ClipRectStack.back(); } // 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() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times. return; // 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->WriteAccessed) g.CurrentWindow->Active = false; End(); if (g.ActiveId == 0 && g.HoveredId == 0) { if (!g.NavWindow || !g.NavWindow->Appearing) // Unless we just made a window/popup appear { // Click to focus window and start moving (after we're done with all our widgets) if (g.IO.MouseClicked[0]) { if (g.HoveredRootWindow != NULL) { // Set ActiveId even if the _NoMove flag is set, without it dragging away from a window with _NoMove would activate hover on other windows. FocusWindow(g.HoveredWindow); SetActiveID(g.HoveredWindow->MoveId, g.HoveredWindow); g.NavDisableHighlight = true; g.ActiveIdClickOffset = g.IO.MousePos - g.HoveredRootWindow->Pos; if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove) && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoMove)) g.MovingWindow = g.HoveredWindow; } else if (g.NavWindow != NULL && GetFrontMostModalRootWindow() == NULL) { // Clicking on void disable focus FocusWindow(NULL); } } // With right mouse button we close popups without changing focus // (The left mouse button path calls FocusWindow which will lead NewFrame->ClosePopupsOverWindow to trigger) if (g.IO.MouseClicked[1]) { // Find the top-most window between HoveredWindow and the front most Modal Window. // This is where we can trim the popup stack. ImGuiWindow* modal = GetFrontMostModalRootWindow(); bool hovered_window_above_modal = false; if (modal == NULL) hovered_window_above_modal = true; for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--) { ImGuiWindow* window = g.Windows[i]; if (window == modal) break; if (window == g.HoveredWindow) hovered_window_above_modal = true; } ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal); } } } // 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 = g.IO.MouseWheelH = 0.0f; memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs)); 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 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) { // Gather windows to render g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0; g.DrawDataBuilder.Clear(); ImGuiWindow* window_to_render_front_most = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget : NULL; for (int n = 0; n != g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0 && window != window_to_render_front_most) AddWindowToDrawDataSelectLayer(window); } if (window_to_render_front_most && window_to_render_front_most->Active && window_to_render_front_most->HiddenFrames <= 0) // NavWindowingTarget is always temporarily displayed as the front-most window AddWindowToDrawDataSelectLayer(window_to_render_front_most); g.DrawDataBuilder.FlattenIntoSingleLayer(); // Draw software mouse cursor if requested ImVec2 offset, size, uv[4]; if (g.IO.MouseDrawCursor && g.IO.Fonts->GetMouseCursorTexData(g.MouseCursor, &offset, &size, &uv[0], &uv[2])) { const ImVec2 pos = g.IO.MousePos - offset; const ImTextureID tex_id = g.IO.Fonts->TexID; const float sc = g.Style.MouseCursorScale; g.OverlayDrawList.PushTextureID(tex_id); g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(1,0)*sc, pos+ImVec2(1,0)*sc + size*sc, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(2,0)*sc, pos+ImVec2(2,0)*sc + size*sc, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow g.OverlayDrawList.AddImage(tex_id, pos, pos + size*sc, uv[2], uv[3], IM_COL32(0,0,0,255)); // Black border g.OverlayDrawList.AddImage(tex_id, pos, pos + size*sc, uv[0], uv[1], IM_COL32(255,255,255,255)); // White fill g.OverlayDrawList.PopTextureID(); } if (!g.OverlayDrawList.VtxBuffer.empty()) AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.OverlayDrawList); // Setup ImDrawData structure for end-user SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData); g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount; g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount; // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData() #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) g.IO.RenderDrawListsFn(&g.DrawData); #endif } } 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; 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, ...) { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; va_list args; va_start(args, fmt); if (g.LogFile) { vfprintf(g.LogFile, fmt, args); } else { g.LogClipboard->appendfv(fmt, args); } va_end(args); } // 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 LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!text_end) text_end = ImGui::FindRenderedTextEnd(text, text_end); const bool log_new_line = ref_pos && (ref_pos->y > window->DC.LogLinePosY + 1); if (ref_pos) window->DC.LogLinePosY = ref_pos->y; const char* text_remaining = text; if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth g.LogStartDepth = window->DC.TreeDepth; const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth); for (;;) { // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. const char* line_end = text_remaining; while (line_end < text_end) if (*line_end == '\n') break; else line_end++; if (line_end >= text_end) line_end = NULL; const bool is_first_line = (text == text_remaining); bool is_last_line = false; if (line_end == NULL) { is_last_line = true; line_end = text_end; } if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0)) { const int char_count = (int)(line_end - text_remaining); if (log_new_line || !is_first_line) ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining); else ImGui::LogText(" %.*s", char_count, text_remaining); } if (is_last_line) break; text_remaining = line_end + 1; } } // Internal ImGui functions to render text // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // Hide anything after a '##' string const char* text_display_end; if (hide_text_after_hash) { text_display_end = FindRenderedTextEnd(text, text_end); } else { if (!text_end) text_end = text + strlen(text); // FIXME-OPT text_display_end = text_end; } const int text_len = (int)(text_display_end - text); if (text_len > 0) { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); if (g.LogEnabled) LogRenderedText(&pos, text, text_display_end); } } void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!text_end) text_end = text + strlen(text); // FIXME-OPT const int text_len = (int)(text_end - text); if (text_len > 0) { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); if (g.LogEnabled) LogRenderedText(&pos, text, text_end); } } // 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) { // Hide anything after a '##' string const char* text_display_end = FindRenderedTextEnd(text, text_end); const int text_len = (int)(text_display_end - text); if (text_len == 0) return; ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // 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); 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); // 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 void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); const float border_size = g.Style.FrameBorderSize; if (border && border_size > 0.0f) { window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const float border_size = g.Style.FrameBorderSize; if (border_size > 0.0f) { window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } // Render a triangle to denote expanded/collapsed state void ImGui::RenderTriangle(ImVec2 p_min, ImGuiDir dir, float scale) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const float h = g.FontSize * 1.00f; float r = h * 0.40f * scale; ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale); ImVec2 a, b, c; switch (dir) { case ImGuiDir_Up: case ImGuiDir_Down: if (dir == ImGuiDir_Up) r = -r; center.y -= r * 0.25f; a = ImVec2(0,1) * r; b = ImVec2(-0.866f,-0.5f) * r; c = ImVec2(+0.866f,-0.5f) * r; break; case ImGuiDir_Left: case ImGuiDir_Right: if (dir == ImGuiDir_Left) r = -r; center.x -= r * 0.25f; a = ImVec2(1,0) * r; b = ImVec2(-0.500f,+0.866f) * r; c = ImVec2(-0.500f,-0.866f) * r; break; case ImGuiDir_None: case ImGuiDir_Count_: IM_ASSERT(0); break; } window->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text)); } void ImGui::RenderBullet(ImVec2 pos) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8); } void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; float thickness = ImMax(sz / 5.0f, 1.0f); sz -= thickness*0.5f; pos += ImVec2(thickness*0.25f, thickness*0.25f); float third = sz / 3.0f; float bx = pos.x + third; float by = pos.y + sz - third*0.5f; window->DrawList->PathLineTo(ImVec2(bx - third, by - third)); window->DrawList->PathLineTo(ImVec2(bx, by)); window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2)); window->DrawList->PathStroke(col, false, thickness); } void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags) { ImGuiContext& g = *GImGui; if (id != g.NavId) return; if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw)) return; ImGuiWindow* window = ImGui::GetCurrentWindow(); if (window->DC.NavHideHighlightOneFrame) return; float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding; ImRect display_rect = bb; display_rect.ClipWith(window->ClipRect); if (flags & ImGuiNavHighlightFlags_TypeDefault) { const float THICKNESS = 2.0f; const float DISTANCE = 3.0f + THICKNESS * 0.5f; display_rect.Expand(ImVec2(DISTANCE,DISTANCE)); bool fully_visible = window->ClipRect.Contains(display_rect); if (!fully_visible) window->DrawList->PushClipRect(display_rect.Min, display_rect.Max); window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS); if (!fully_visible) window->DrawList->PopClipRect(); } if (flags & ImGuiNavHighlightFlags_TypeThin) { window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f); } } // 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) { ImGuiContext& g = *GImGui; const char* text_display_end; if (hide_text_after_double_hash) 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->AdvanceX field) 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. // 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) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.LogEnabled) { // If logging is active, do not perform any clipping *out_items_display_start = 0; *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; int start = (int)((window->ClipRect.Min.y - pos.y) / items_height); int end = (int)((window->ClipRect.Max.y - pos.y) / items_height); if (g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Up) // When performing a navigation request, ensure we have one item extra in the direction we are moving to start--; if (g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down) end++; 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) { ImGuiContext& g = *GImGui; for (int i = g.Windows.Size - 1; i >= 0; i--) { ImGuiWindow* window = g.Windows[i]; if (!window->Active) continue; if (window->Flags & ImGuiWindowFlags_NoInputs) continue; // Using the clipped AABB, a child window will typically be clipped by its parent (not always) ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding); if (bb.Contains(pos)) return window; } return NULL; } // 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) bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // Clip ImRect rect_clipped(r_min, r_max); if (clip) rect_clipped.ClipWith(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); } static bool IsKeyPressedMap(ImGuiKey key, bool repeat) { const int key_index = GImGui->IO.KeyMap[key]; return (key_index >= 0) ? ImGui::IsKeyPressed(key_index, repeat) : false; } int ImGui::GetKeyIndex(ImGuiKey imgui_key) { IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT); return GImGui->IO.KeyMap[imgui_key]; } // Note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your back-end/engine stored them into KeyDown[]! bool ImGui::IsKeyDown(int user_key_index) { if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); return GImGui->IO.KeysDown[user_key_index]; } int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate) { if (t == 0.0f) return 1; if (t <= repeat_delay || repeat_rate <= 0.0f) return 0; const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate); return (count > 0) ? count : 0; } int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate) { 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.KeysDownDuration[key_index]; return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate); } bool ImGui::IsKeyPressed(int user_key_index, bool repeat) { ImGuiContext& g = *GImGui; if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); const float t = g.IO.KeysDownDuration[user_key_index]; if (t == 0.0f) return true; if (repeat && t > g.IO.KeyRepeatDelay) return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0; return false; } bool ImGui::IsKeyReleased(int user_key_index) { ImGuiContext& g = *GImGui; if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index]; } 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::IsAnyMouseDown() { ImGuiContext& g = *GImGui; for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++) if (g.IO.MouseDown[n]) return true; return false; } bool ImGui::IsMouseClicked(int button, bool repeat) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); const float t = g.IO.MouseDownDuration[button]; if (t == 0.0f) return true; 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) { 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) { 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; } 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].OpenMousePos; return g.IO.MousePos; } // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position bool ImGui::IsMousePosValid(const ImVec2* mouse_pos) { if (mouse_pos == NULL) mouse_pos = &GImGui->IO.MousePos; const float MOUSE_INVALID = -256000.0f; return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID; } // NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; if (g.IO.MouseDown[button]) if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment). 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; } void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) { GImGui->MouseCursor = cursor_type; } void ImGui::CaptureKeyboardFromApp(bool capture) { GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0; } void ImGui::CaptureMouseFromApp(bool capture) { GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0; } bool ImGui::IsItemActive() { ImGuiContext& g = *GImGui; if (g.ActiveId) { ImGuiWindow* window = g.CurrentWindow; return g.ActiveId == window->DC.LastItemId; } return false; } bool ImGui::IsItemFocused() { ImGuiContext& g = *GImGui; return g.NavId && !g.NavDisableHighlight && g.NavId == g.CurrentWindow->DC.LastItemId; } bool ImGui::IsItemClicked(int mouse_button) { return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_Default); } bool ImGui::IsAnyItemHovered() { ImGuiContext& g = *GImGui; return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0; } bool ImGui::IsAnyItemActive() { ImGuiContext& g = *GImGui; return g.ActiveId != 0; } bool ImGui::IsAnyItemFocused() { ImGuiContext& g = *GImGui; return g.NavId != 0 && !g.NavDisableHighlight; } bool ImGui::IsItemVisible() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ClipRect.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 = GetCurrentWindowRead(); return window->DC.LastItemRect.Min; } ImVec2 ImGui::GetItemRectMax() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Max; } ImVec2 ImGui::GetItemRectSize() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.GetSize(); } static ImRect GetViewportRect() { 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); } // Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first. void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip) { ImGuiContext& g = *GImGui; char window_name[16]; ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount); if (override_previous_tooltip) if (ImGuiWindow* window = FindWindowByName(window_name)) if (window->Active) { // Hide previous tooltips. We can't easily "reset" the content of a window so we create a new one. window->HiddenFrames = 1; ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount); } ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoNav; Begin(window_name, NULL, flags | extra_flags); } void ImGui::SetTooltipV(const char* fmt, va_list args) { BeginTooltipEx(0, true); TextV(fmt, args); EndTooltip(); } void ImGui::SetTooltip(const char* fmt, ...) { va_list args; va_start(args, fmt); SetTooltipV(fmt, args); va_end(args); } void ImGui::BeginTooltip() { BeginTooltipEx(0, false); } void ImGui::EndTooltip() { IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls End(); } // 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(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; int current_stack_size = g.CurrentPopupStack.Size; ImGuiPopupRef popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. popup_ref.PopupId = id; popup_ref.Window = NULL; popup_ref.ParentWindow = parent_window; popup_ref.OpenFrameCount = g.FrameCount; popup_ref.OpenParentId = parent_window->IDStack.back(); popup_ref.OpenMousePos = g.IO.MousePos; popup_ref.OpenPopupPos = (!g.NavDisableHighlight && g.NavDisableMouseHover) ? NavCalcPreferredMousePos() : g.IO.MousePos; if (g.OpenPopupStack.Size < current_stack_size + 1) { g.OpenPopupStack.push_back(popup_ref); } else { // Close child popups if any g.OpenPopupStack.resize(current_stack_size + 1); // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand. if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount; else g.OpenPopupStack[current_stack_size] = popup_ref; // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow(). // This is equivalent to what ClosePopupToLevel() does. //if (g.OpenPopupStack[current_stack_size].PopupId == id) // FocusWindow(parent_window); } } void ImGui::OpenPopup(const char* str_id) { ImGuiContext& g = *GImGui; OpenPopupEx(g.CurrentWindow->GetID(str_id)); } void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window) { 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 (ref_window) { 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; // Trim the stack if popups are not direct descendant of the reference window (which is often the NavWindow) 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 == ref_window->RootWindow); if (!has_focus) break; } } if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the block below ClosePopupToLevel(n); } static ImGuiWindow* GetFrontMostModalRootWindow() { ImGuiContext& g = *GImGui; for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window) if (popup->Flags & ImGuiWindowFlags_Modal) return popup; return NULL; } static void ClosePopupToLevel(int remaining) { IM_ASSERT(remaining >= 0); ImGuiContext& g = *GImGui; ImGuiWindow* focus_window = (remaining > 0) ? g.OpenPopupStack[remaining-1].Window : g.OpenPopupStack[0].ParentWindow; if (g.NavLayer == 0) focus_window = NavRestoreLastChildNavWindow(focus_window); ImGui::FocusWindow(focus_window); focus_window->DC.NavHideHighlightOneFrame = true; g.OpenPopupStack.resize(remaining); } void ImGui::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); } bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; if (!IsPopupOpen(id)) { g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values return false; } char name[20]; if (extra_flags & ImGuiWindowFlags_ChildMenu) ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth else ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup); if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) EndPopup(); return is_open; } bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.Size <= g.CurrentPopupStack.Size) // Early out for performance { g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values return false; } return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } bool ImGui::IsPopupOpen(ImGuiID id) { ImGuiContext& g = *GImGui; return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id; } bool ImGui::IsPopupOpen(const char* str_id) { ImGuiContext& g = *GImGui; return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id); } bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = window->GetID(name); if (!IsPopupOpen(id)) { g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values return false; } // Center modal windows by default // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. if (g.NextWindowData.PosCond == 0) SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); bool is_open = Begin(name, p_open, flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings); if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) { EndPopup(); if (is_open) ClosePopup(id); return false; } return is_open; } static void NavProcessMoveRequestWrapAround(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.NavWindow == window && NavMoveRequestButNoResultYet()) if ((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == 0) { g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued; NavMoveRequestCancel(); g.NavWindow->NavRectRel[0].Min.y = g.NavWindow->NavRectRel[0].Max.y = ((g.NavMoveDir == ImGuiDir_Up) ? ImMax(window->SizeFull.y, window->SizeContents.y) : 0.0f) - window->Scroll.y; } } void ImGui::EndPopup() { ImGuiContext& g = *GImGui; (void)g; IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls IM_ASSERT(g.CurrentPopupStack.Size > 0); // Make all menus and popups wrap around for now, may need to expose that policy. NavProcessMoveRequestWrapAround(g.CurrentWindow); End(); } bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) OpenPopupEx(id); return true; } return false; } // This is a helper to handle the simplest case of associating one named popup to one given widget. // You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). // You can pass a NULL str_id to use the identifier of the last item. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items) { if (!str_id) str_id = "window_context"; ImGuiID id = GImGui->CurrentWindow->GetID(str_id); if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) if (also_over_items || !IsAnyItemHovered()) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) { if (!str_id) str_id = "void_context"; ImGuiID id = GImGui->CurrentWindow->GetID(str_id); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = ImGui::GetCurrentWindow(); ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag const ImVec2 content_avail = ImGui::GetContentRegionAvail(); ImVec2 size = ImFloor(size_arg); const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00); if (size.x <= 0.0f) size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues) if (size.y <= 0.0f) size.y = ImMax(content_avail.y + size.y, 4.0f); const float backup_border_size = g.Style.ChildBorderSize; if (!border) g.Style.ChildBorderSize = 0.0f; flags |= extra_flags; char title[256]; if (name) ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id); else ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id); ImGui::SetNextWindowSize(size); bool ret = ImGui::Begin(title, NULL, flags); ImGuiWindow* child_window = ImGui::GetCurrentWindow(); child_window->ChildId = id; child_window->AutoFitChildAxises = auto_fit_axises; g.Style.ChildBorderSize = backup_border_size; // Process navigation-in immediately so NavInit can run on first frame if (!(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll) && g.NavActivateId == id) { ImGui::FocusWindow(child_window); ImGui::NavInitWindow(child_window, false); ImGui::SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item g.ActiveIdSource = ImGuiInputSource_Nav; } return ret; } bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags); } bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { IM_ASSERT(id != 0); return BeginChildEx(NULL, id, size_arg, border, extra_flags); } void ImGui::EndChild() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss if (window->BeginCount > 1) { 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. ImVec2 sz = GetWindowSize(); if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // 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->AutoFitChildAxises & (1 << ImGuiAxis_Y)) sz.y = ImMax(4.0f, sz.y); End(); ImGuiWindow* parent_window = g.CurrentWindow; ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz); ItemSize(sz); if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened)) { ItemAdd(bb, window->ChildId); RenderNavHighlight(bb, window->ChildId); // When browsing a window that has no activable items (scroll only) we keep a highlight on the child if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow) RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin); } else { // Not navigable into ItemAdd(bb, 0); } } } // Helper to create a child window / scrolling region that looks like a normal widget frame. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]); PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); return BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); } void ImGui::EndChildFrame() { EndChild(); PopStyleVar(3); PopStyleColor(); } // Save and compare stack sizes on Begin()/End() to detect usage errors static void CheckStacksSize(ImGuiWindow* window, bool write) { // 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 or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop() { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many 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++;}// Too few or too many EndMenu()/EndPopup() { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor() { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar() { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont() IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); } enum ImGuiPopupPositionPolicy { ImGuiPopupPositionPolicy_Default, ImGuiPopupPositionPolicy_ComboBox }; static ImVec2 FindBestWindowPosForPopup(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default) { const ImGuiStyle& style = GImGui->Style; // r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) // r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it. ImVec2 safe_padding = style.DisplaySafeAreaPadding; ImRect r_outer(GetViewportRect()); r_outer.Expand(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(ref_pos, r_outer.Min, r_outer.Max - size); //GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255)); //GImGui->OverlayDrawList.AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255)); // Combo Box policy (we want a connecting edge) if (policy == ImGuiPopupPositionPolicy_ComboBox) { const ImGuiDir dir_prefered_order[ImGuiDir_Count_] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up }; for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_Count_; n++) { const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; if (n != -1 && dir == *last_dir) // Already tried this direction? continue; ImVec2 pos; if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default) if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left if (!r_outer.Contains(ImRect(pos, pos + size))) continue; *last_dir = dir; return pos; } } // Default popup policy const ImGuiDir dir_prefered_order[ImGuiDir_Count_] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left }; for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_Count_; n++) { const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; if (n != -1 && dir == *last_dir) // Already tried this direction? continue; float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); if (avail_w < size.x || avail_h < size.y) continue; ImVec2 pos; pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x; pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y; *last_dir = dir; return pos; } // Fallback, try to keep within display *last_dir = ImGuiDir_None; ImVec2 pos = ref_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; } static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled) { window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags); window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags); window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags); } ImGuiWindow* ImGui::FindWindowByName(const char* name) { ImGuiContext& g = *GImGui; ImGuiID id = ImHash(name, 0); return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id); } static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; // Create window the first time ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name); window->Flags = flags; g.WindowsById.SetVoidPtr(window->ID, window); // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. if (!(flags & ImGuiWindowFlags_NoSavedSettings)) { // Retrieve settings from .ini file // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. window->Pos = window->PosFloat = ImVec2(60, 60); if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID)) { SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); window->PosFloat = settings->Pos; window->Pos = ImFloor(window->PosFloat); window->Collapsed = settings->Collapsed; if (ImLengthSqr(settings->Size) > 0.00001f) size = settings->Size; } } window->Size = window->SizeFull = window->SizeFullAtLastBegin = size; if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { window->AutoFitFramesX = window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } else { 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); } 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; } static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) { ImGuiContext& g = *GImGui; if (g.NextWindowData.SizeConstraintCond != 0) { // Using -1,-1 on either X/Y axis to preserve the current size. ImRect cr = g.NextWindowData.SizeConstraintRect; 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.NextWindowData.SizeCallback) { ImGuiSizeCallbackData data; data.UserData = g.NextWindowData.SizeCallbackUserData; data.Pos = window->Pos; data.CurrentSize = window->SizeFull; data.DesiredSize = new_size; g.NextWindowData.SizeCallback(&data); new_size = data.DesiredSize; } } // Minimum size if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) { new_size = ImMax(new_size, g.Style.WindowMinSize); new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows } return new_size; } static ImVec2 CalcSizeContents(ImGuiWindow* window) { ImVec2 sz; sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x)); sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y)); return sz + window->WindowPadding; } static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; ImGuiWindowFlags flags = window->Flags; 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 = size_contents; } else { // When the window cannot fit all contents (either because of constraints, either because screen is too small): we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding. size_auto_fit = ImClamp(size_contents, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding)); ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit); if (size_auto_fit_after_constraint.x < size_contents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)) size_auto_fit.y += style.ScrollbarSize; if (size_auto_fit_after_constraint.y < size_contents.y && !(flags & ImGuiWindowFlags_NoScrollbar)) size_auto_fit.x += style.ScrollbarSize; } return size_auto_fit; } static float GetScrollMaxX(ImGuiWindow* window) { return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x)); } static float GetScrollMaxY(ImGuiWindow* window) { return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y)); } static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) { ImVec2 scroll = window->Scroll; float cr_x = window->ScrollTargetCenterRatio.x; float cr_y = window->ScrollTargetCenterRatio.y; if (window->ScrollTarget.x < FLT_MAX) scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x); if (window->ScrollTarget.y < FLT_MAX) scroll.y = window->ScrollTarget.y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y); scroll = ImMax(scroll, ImVec2(0.0f, 0.0f)); if (!window->Collapsed && !window->SkipItems) { scroll.x = ImMin(scroll.x, GetScrollMaxX(window)); scroll.y = ImMin(scroll.y, GetScrollMaxY(window)); } return scroll; } static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags) { if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) return ImGuiCol_PopupBg; if (flags & ImGuiWindowFlags_ChildWindow) return ImGuiCol_ChildBg; return ImGuiCol_WindowBg; } static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size) { ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right ImVec2 size_expected = pos_max - pos_min; ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected); *out_pos = pos_min; if (corner_norm.x == 0.0f) out_pos->x -= (size_constrained.x - size_expected.x); if (corner_norm.y == 0.0f) out_pos->y -= (size_constrained.y - size_expected.y); *out_size = size_constrained; } struct ImGuiResizeGripDef { ImVec2 CornerPos; ImVec2 InnerDir; int AngleMin12, AngleMax12; }; const ImGuiResizeGripDef resize_grip_def[4] = { { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right }; static ImRect GetBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness) { ImRect rect = window->Rect(); if (thickness == 0.0f) rect.Max -= ImVec2(1,1); if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y, rect.Max.x - perp_padding, rect.Min.y + thickness); if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x, rect.Max.y - perp_padding); if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y); if (border_n == 3) return ImRect(rect.Min.x, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); IM_ASSERT(0); return ImRect(); } // Handle resize for: Resize Grips, Borders, Gamepad static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) return; const int resize_border_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 4 : 0; const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); const float grip_hover_size = (float)(int)(grip_draw_size * 0.75f); ImVec2 pos_target(FLT_MAX, FLT_MAX); ImVec2 size_target(FLT_MAX, FLT_MAX); // Manual resize grips PushID("#RESIZE"); for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) { const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos); // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window ImRect resize_rect(corner, corner + grip.InnerDir * grip_hover_size); resize_rect.FixInverted(); bool hovered, held; ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); if (hovered || held) g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE; if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0) { // Manual auto-fit when double-clicking size_target = CalcSizeAfterConstraint(window, size_auto_fit); ClearActiveID(); } else if (held) { // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize() * grip.CornerPos; // Corner of the window corresponding to our corner grip CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPos, &pos_target, &size_target); } if (resize_grip_n == 0 || held || hovered) resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); } for (int border_n = 0; border_n < resize_border_count; border_n++) { const float BORDER_SIZE = 5.0f; // FIXME: Only works _inside_ window because of HoveredWindow check. const float BORDER_APPEAR_TIMER = 0.05f; // Reduce visual noise bool hovered, held; ImRect border_rect = GetBorderRect(window, border_n, grip_hover_size, BORDER_SIZE); ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren); if ((hovered && g.HoveredIdTimer > BORDER_APPEAR_TIMER) || held) { g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS; if (held) *border_held = border_n; } if (held) { ImVec2 border_target = window->Pos; ImVec2 border_posn; if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y); } if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + BORDER_SIZE); } if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + BORDER_SIZE); } if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x); } CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } } PopID(); // Navigation/gamepad resize if (g.NavWindowingTarget == window) { ImVec2 nav_resize_delta; if (g.NavWindowingInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift) nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down); if (g.NavWindowingInputSource == ImGuiInputSource_NavGamepad) nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down); if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f) { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck. size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta); } } // Apply back modified position/size to window if (size_target.x != FLT_MAX) { window->SizeFull = size_target; MarkIniSettingsDirty(window); } if (pos_target.x != FLT_MAX) { window->Pos = window->PosFloat = ImFloor(pos_target); MarkIniSettingsDirty(window); } window->Size = window->SizeFull; } // 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). // 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_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. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { 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(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet // Find or create ImGuiWindow* window = FindWindowByName(name); if (!window) { ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here. window = CreateNewWindow(name, size_on_first_use, flags); } // Automatically disable manual moving/resizing when NoInputs is set if (flags & ImGuiWindowFlags_NoInputs) flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; if (flags & ImGuiWindowFlags_NavFlattened) IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow); const int current_frame = g.FrameCount; 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; // Update the Appearing flag bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFrames == 1); if (flags & ImGuiWindowFlags_Popup) { ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size]; window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed window_just_activated_by_user |= (window != popup_ref.Window); } window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize); window->CloseButton = (p_open != NULL); if (window->Appearing) SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back(); ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow; IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); // Add to stack g.CurrentWindowStack.push_back(window); SetCurrentWindow(window); CheckStacksSize(window, true); if (flags & ImGuiWindowFlags_Popup) { ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size]; popup_ref.Window = window; g.CurrentPopupStack.push_back(popup_ref); window->PopupId = popup_ref.PopupId; } if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow)) window->NavLastIds[0] = 0; // Process SetNextWindow***() calls bool window_pos_set_by_api = false; bool window_size_x_set_by_api = false, window_size_y_set_by_api = false; if (g.NextWindowData.PosCond) { window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0; if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f) { // May be processed on the next frame if this is our first frame and we are measuring size // FIXME: Look into removing the branch so everything can go through this same code path for consistency. window->SetWindowPosVal = g.NextWindowData.PosVal; window->SetWindowPosPivot = g.NextWindowData.PosPivotVal; window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); } else { SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond); } g.NextWindowData.PosCond = 0; } if (g.NextWindowData.SizeCond) { window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f); window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f); SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond); g.NextWindowData.SizeCond = 0; } if (g.NextWindowData.ContentSizeCond) { // Adjust passed "client size" to become a "window size" window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal; if (window->SizeContentsExplicit.y != 0.0f) window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight(); g.NextWindowData.ContentSizeCond = 0; } else if (first_begin_of_the_frame) { window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); } if (g.NextWindowData.CollapsedCond) { SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); g.NextWindowData.CollapsedCond = 0; } if (g.NextWindowData.FocusCond) { SetWindowFocus(); g.NextWindowData.FocusCond = 0; } if (window->Appearing) SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false); // When reusing window again multiple times a frame, just append content (don't need to setup again) if (first_begin_of_the_frame) { const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) // Initialize window->ParentWindow = parent_window; window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForTabbing = window->RootWindowForNav = window; if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !window_is_child_tooltip) window->RootWindow = parent_window->RootWindow; if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) window->RootWindowForTitleBarHighlight = window->RootWindowForTabbing = parent_window->RootWindowForTitleBarHighlight; // Same value in master branch, will differ for docking while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened) window->RootWindowForNav = window->RootWindowForNav->ParentWindow; window->Active = true; window->BeginOrderWithinParent = 0; window->BeginOrderWithinContext = g.WindowsActiveCount++; window->BeginCount = 0; window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); window->LastFrameActive = current_frame; window->IDStack.resize(1); // Lock window rounding, border size and rounding so that altering the border sizes for children doesn't have side-effects. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; window->WindowBorderSize = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildBorderSize : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize; window->WindowPadding = style.WindowPadding; if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f) window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f); // 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)) { ImRect title_bar_rect = window->TitleBarRect(); if (window->CollapseToggleWanted || (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])) { window->Collapsed = !window->Collapsed; MarkIniSettingsDirty(window); FocusWindow(window); } } else { window->Collapsed = false; } window->CollapseToggleWanted = false; // SIZE // Update contents size from last frame for auto-fitting (unless explicitly specified) window->SizeContents = CalcSizeContents(window); // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows) if (window->HiddenFrames > 0) window->HiddenFrames--; if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && window_just_activated_by_user) { window->HiddenFrames = 1; if (flags & ImGuiWindowFlags_AlwaysAutoResize) { if (!window_size_x_set_by_api) window->Size.x = window->SizeFull.x = 0.f; if (!window_size_y_set_by_api) window->Size.y = window->SizeFull.y = 0.f; window->SizeContents = ImVec2(0.f, 0.f); } } // Calculate auto-fit size, handle automatic resize const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents); ImVec2 size_full_modified(FLT_MAX, FLT_MAX); if (flags & ImGuiWindowFlags_AlwaysAutoResize && !window->Collapsed) { // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. if (!window_size_x_set_by_api) window->SizeFull.x = size_full_modified.x = size_auto_fit.x; if (!window_size_y_set_by_api) window->SizeFull.y = size_full_modified.y = size_auto_fit.y; } else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) { // Auto-fit only grows during the first few frames // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0) window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; if (!window_size_y_set_by_api && window->AutoFitFramesY > 0) window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; if (!window->Collapsed) MarkIniSettingsDirty(window); } // Apply minimum/maximum window size constraints and final size window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull); window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull; // SCROLLBAR STATUS // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size). if (!window->Collapsed) { // When reading the current size we need to read it after size constraints have been applied float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x; float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y; window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); if (window->ScrollbarX && !window->ScrollbarY) window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar); window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); } // POSITION // Popup latch its initial position, will position itself when it appears next frame if (window_just_activated_by_user) { window->AutoPosLastDirection = ImGuiDir_None; if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) window->Pos = window->PosFloat = g.CurrentPopupStack.back().OpenPopupPos; } // Position child window if (flags & ImGuiWindowFlags_ChildWindow) { window->BeginOrderWithinParent = parent_window->DC.ChildWindows.Size; parent_window->DC.ChildWindows.push_back(window); if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip) window->Pos = window->PosFloat = parent_window->DC.CursorPos; } const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFrames == 0); if (window_pos_with_pivot) { // Position given a pivot (e.g. for centering) SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0); } else if (flags & ImGuiWindowFlags_ChildMenu) { // Child menus typically request _any_ position within the parent menu item, and then our FindBestPopupWindowPos() function will move the new menu outside the parent bounds. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. IM_ASSERT(window_pos_set_by_api); float horizontal_overlap = style.ItemSpacing.x; // We want some overlap to convey the relative depth of each popup (currently the amount of overlap it is hard-coded to style.ItemSpacing.x, may need to introduce another style value). ImGuiWindow* parent_menu = parent_window_in_stack; ImRect rect_to_avoid; if (parent_menu->DC.MenuBarAppending) rect_to_avoid = ImRect(-FLT_MAX, parent_menu->Pos.y + parent_menu->TitleBarHeight(), FLT_MAX, parent_menu->Pos.y + parent_menu->TitleBarHeight() + parent_menu->MenuBarHeight()); else rect_to_avoid = ImRect(parent_menu->Pos.x + horizontal_overlap, -FLT_MAX, parent_menu->Pos.x + parent_menu->Size.x - horizontal_overlap - parent_menu->ScrollbarSizes.x, FLT_MAX); window->PosFloat = FindBestWindowPosForPopup(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); } else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize) { ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1); window->PosFloat = FindBestWindowPosForPopup(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); } // Position tooltip (always follows mouse) if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip) { float sc = g.Style.MouseCursorScale; ImVec2 ref_pos = (!g.NavDisableHighlight && g.NavDisableMouseHover) ? NavCalcPreferredMousePos() : g.IO.MousePos; ImRect rect_to_avoid; if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.NavFlags & ImGuiNavFlags_MoveMouse)) rect_to_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8); else rect_to_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important. window->PosFloat = FindBestWindowPosForPopup(ref_pos, window->Size, &window->AutoPosLastDirection, rect_to_avoid); if (window->AutoPosLastDirection == ImGuiDir_None) window->PosFloat = ref_pos + 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 position so it stays visible if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) { 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 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->Pos = ImFloor(window->PosFloat); // Default item width. Make it proportional to window size if window manually resizes if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); else window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); // Prepare for focus requests 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 = INT_MAX; // Apply scrolling window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window); window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); // Apply focus, new windows appears in front bool want_focus = false; if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup)) want_focus = true; // Handle manual resize: Resize Grips, Borders, Gamepad int border_held = -1; ImU32 resize_grip_col[4] = { 0 }; const int resize_grip_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 2 : 1; // 4 const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); if (!window->Collapsed) UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]); // DRAWING // Setup draw list and outer clipping rectangle window->DrawList->Clear(); window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); ImRect viewport_rect(GetViewportRect()); if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true); else PushClipRect(viewport_rect.Min, viewport_rect.Max, true); // Draw modal window background (darkens what is behind them) if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow()) window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio)); // Draw navigation selection/windowing rectangle background if (g.NavWindowingTarget == window) { ImRect bb = window->Rect(); bb.Expand(g.FontSize); if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding); } // Draw window + handle manual resize const float window_rounding = window->WindowRounding; const float window_border_size = window->WindowBorderSize; const bool title_bar_is_highlight = want_focus || (g.NavWindow && window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight); const ImRect title_bar_rect = window->TitleBarRect(); if (window->Collapsed) { // Title bar only float backup_border_size = style.FrameBorderSize; g.Style.FrameBorderSize = window->WindowBorderSize; ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed); RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding); g.Style.FrameBorderSize = backup_border_size; } else { // Window background ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags)); if (g.NextWindowData.BgAlphaCond != 0) { bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT); g.NextWindowData.BgAlphaCond = 0; } window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot); // Title bar ImU32 title_bar_col = GetColorU32(window->Collapsed ? ImGuiCol_TitleBgCollapsed : title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); if (!(flags & ImGuiWindowFlags_NoTitleBar)) window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top); // Menu bar if (flags & ImGuiWindowFlags_MenuBar) { ImRect menu_bar_rect = window->MenuBarRect(); menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top); if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); } // Scrollbars if (window->ScrollbarX) Scrollbar(ImGuiLayoutType_Horizontal); if (window->ScrollbarY) Scrollbar(ImGuiLayoutType_Vertical); // Render resize grips (after their input handling so we don't have a frame of latency) if (!(flags & ImGuiWindowFlags_NoResize)) { for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) { const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos); window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, grip_draw_size) : ImVec2(grip_draw_size, window_border_size))); window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(grip_draw_size, window_border_size) : ImVec2(window_border_size, grip_draw_size))); window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12); window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]); } } // Borders if (window_border_size > 0.0f) window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding, ImDrawCornerFlags_All, window_border_size); if (border_held != -1) { ImRect border = GetBorderRect(window, border_held, grip_draw_size, 0.0f); window->DrawList->AddLine(border.Min, border.Max, GetColorU32(ImGuiCol_SeparatorActive), ImMax(1.0f, window_border_size)); } if (style.FrameBorderSize > 0 && !(flags & ImGuiWindowFlags_NoTitleBar)) window->DrawList->AddLine(title_bar_rect.GetBL() + ImVec2(style.WindowBorderSize, -1), title_bar_rect.GetBR() + ImVec2(-style.WindowBorderSize,-1), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); } // Draw navigation selection/windowing rectangle border if (g.NavWindowingTarget == window) { float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding); ImRect bb = window->Rect(); bb.Expand(g.FontSize); if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward { bb.Expand(-g.FontSize - 1.0f); rounding = window->WindowRounding; } window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f); } // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars. window->SizeFullAtLastBegin = window->SizeFull; // 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 // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) 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.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.NavHideHighlightOneFrame = false; window->DC.NavHasScroll = (GetScrollMaxY() > 0.0f); window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; window->DC.NavLayerActiveMaskNext = 0x00; 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.LayoutType = ImGuiLayoutType_Vertical; window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; window->DC.ItemFlags = ImGuiItemFlags_Default_; window->DC.ItemWidth = window->ItemWidthDefault; window->DC.TextWrapPos = -1.0f; // disabled window->DC.ItemFlagsStack.resize(0); window->DC.ItemWidthStack.resize(0); window->DC.TextWrapPosStack.resize(0); window->DC.ColumnsSet = NULL; window->DC.TreeDepth = 0; window->DC.TreeDepthMayCloseOnPop = 0x00; window->DC.StateStorage = &window->StateStorage; window->DC.GroupStack.resize(0); window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user); if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags)) { window->DC.ItemFlags = parent_window->DC.ItemFlags; window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags); } if (window->AutoFitFramesX > 0) window->AutoFitFramesX--; if (window->AutoFitFramesY > 0) window->AutoFitFramesY--; // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) if (want_focus) { FocusWindow(window); NavInitWindow(window, false); } // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) { // Close & collapse button are on layer 1 (same as menus) and don't default focus const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; window->DC.NavLayerCurrent++; window->DC.NavLayerCurrentMask <<= 1; // Collapse button if (!(flags & ImGuiWindowFlags_NoCollapse)) { ImGuiID id = window->GetID("#COLLAPSE"); ImRect bb(window->Pos + style.FramePadding + ImVec2(1,1), window->Pos + style.FramePadding + ImVec2(g.FontSize,g.FontSize) - ImVec2(1,1)); ItemAdd(bb, id); // To allow navigation if (ButtonBehavior(bb, id, NULL, NULL)) window->CollapseToggleWanted = true; // Defer collapsing to next frame as we are too far in the Begin() function RenderNavHighlight(bb, id); RenderTriangle(window->Pos + style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); } // Close button if (p_open != NULL) { 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; } window->DC.NavLayerCurrent--; window->DC.NavLayerCurrentMask >>= 1; window->DC.ItemFlags = item_flags_backup; // Title text (FIXME: refactor text alignment facilities along with RenderText helpers) ImVec2 text_size = CalcTextSize(name, NULL, true); ImRect text_r = title_bar_rect; float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x; float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x; if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); text_r.Min.x += pad_left; text_r.Max.x -= pad_right; ImRect clip_rect = text_r; clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton() RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); } // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() window->WindowRectClipped = window->Rect(); window->WindowRectClipped.ClipWith(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. // Maybe we can support CTRL+C on every element? /* if (g.ActiveId == move_id) if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C)) ImGui::LogToClipboard(); */ // Inner rectangle // 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. window->InnerRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; window->InnerRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - window->WindowBorderSize; window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize; //window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE); // After Begin() we fill the last item / hovered data using the title bar data. Make that a standard behavior (to allow usage of context menus on title bar only, etc.). window->DC.LastItemId = window->MoveId; window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; window->DC.LastItemRect = title_bar_rect; } // Inner clipping rectangle // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. const float border_size = window->WindowBorderSize; ImRect clip_rect; clip_rect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - border_size))); clip_rect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y); clip_rect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - border_size))); clip_rect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y); PushClipRect(clip_rect.Min, clip_rect.Max, true); // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) if (first_begin_of_the_frame) window->WriteAccessed = false; window->BeginCount++; g.NextWindowData.SizeConstraintCond = 0; // 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). if (flags & ImGuiWindowFlags_ChildWindow) { IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); window->Collapsed = parent_window && parent_window->Collapsed; 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->Active = false; } if (style.Alpha <= 0.0f) 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->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0; return !window->SkipItems; } // Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags) { // Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file. if (size_first_use.x != 0.0f || size_first_use.y != 0.0f) ImGui::SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver); // Old API feature: override the window background alpha with a parameter. if (bg_alpha_override >= 0.0f) ImGui::SetNextWindowBgAlpha(bg_alpha_override); return ImGui::Begin(name, p_open, flags); } #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS void ImGui::End() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->DC.ColumnsSet != NULL) EndColumns(); PopClipRect(); // inner window clip rectangle // Stop logging if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging 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 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. void ImGui::Scrollbar(ImGuiLayoutType direction) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const bool horizontal = (direction == ImGuiLayoutType_Horizontal); const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY"); // Render background 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->WindowBorderSize; 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); if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f) return; int window_rounding_corners; if (horizontal) window_rounding_corners = ImDrawCornerFlags_BotLeft | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight); else window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0) | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight); window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, window_rounding_corners); bb.Expand(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, longer axis of the scrollbar (= height for a vertical 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->SizeFull.x : window->SizeFull.y) - other_scrollbar_size_w; float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y; // Calculate the height of our grabbable box. It 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. IM_ASSERT(ImMax(win_size_contents_v, win_size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. const float win_size_v = ImMax(ImMax(win_size_contents_v, win_size_avail_v), 1.0f); const float grab_h_pixels = ImClamp(scrollbar_size_v * (win_size_avail_v / win_size_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, ImGuiButtonFlags_NoNavFocus); 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) { 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); 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_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm) { *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } else { seek_absolute = true; *click_delta_to_grab_center_v = 0.0f; } } // Apply scroll // 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(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) *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } // Render const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); ImRect grab_rect; if (horizontal) grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, window_rect.Max.x), bb.Max.y); else grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, window_rect.Max.y)); window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding); } void ImGui::BringWindowToFront(ImGuiWindow* window) { ImGuiContext& g = *GImGui; ImGuiWindow* current_front_window = g.Windows.back(); if (current_front_window == window || current_front_window->RootWindow == window) return; for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window if (g.Windows[i] == window) { g.Windows.erase(g.Windows.Data + i); g.Windows.push_back(window); break; } } void ImGui::BringWindowToBack(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.Windows[0] == window) return; for (int i = 0; i < g.Windows.Size; i++) if (g.Windows[i] == window) { memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*)); g.Windows[0] = window; break; } } // Moving window to front of display and set focus (which happens to be back of our sorted list) void ImGui::FocusWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.NavWindow != window) { g.NavWindow = window; if (window && g.NavDisableMouseHover) g.NavMousePosDirty = true; g.NavInitRequest = false; g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId g.NavIdIsAlive = false; g.NavLayer = 0; } // Passing NULL allow to disable keyboard focus if (!window) return; // Move the root window to the top of the pile if (window->RootWindow) window = window->RootWindow; // 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) ClearActiveID(); // Bring to front if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) BringWindowToFront(window); } void ImGui::FocusFrontMostActiveWindow(ImGuiWindow* ignore_window) { ImGuiContext& g = *GImGui; for (int i = g.Windows.Size - 1; i >= 0; i--) if (g.Windows[i] != ignore_window && g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow)) { ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(g.Windows[i]); FocusWindow(focus_window); return; } } void ImGui::PushItemWidth(float item_width) { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); } void ImGui::PushMultiItemsWidths(int components, float w_full) { ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = GImGui->Style; if (w_full <= 0.0f) w_full = 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.ItemWidthStack.pop_back(); window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); } float ImGui::CalcItemWidth() { 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. float width_to_right_edge = GetContentRegionAvail().x; w = ImMax(1.0f, width_to_right_edge + w); } w = (float)(int)w; return w; } static ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } void ImGui::SetCurrentFont(ImFont* font) { 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; g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; ImFontAtlas* atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; } void ImGui::PushFont(ImFont* font) { ImGuiContext& g = *GImGui; if (!font) font = GetDefaultFont(); SetCurrentFont(font); g.FontStack.push_back(font); g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() { ImGuiContext& g = *GImGui; g.CurrentWindow->DrawList->PopTextureID(); g.FontStack.pop_back(); SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back()); } void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (enabled) window->DC.ItemFlags |= option; else window->DC.ItemFlags &= ~option; window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags); } void ImGui::PopItemFlag() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemFlagsStack.pop_back(); window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back(); } void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) { PushItemFlag(ImGuiItemFlags_AllowKeyboardFocus, allow_keyboard_focus); } void ImGui::PopAllowKeyboardFocus() { PopItemFlag(); } void ImGui::PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } void ImGui::PopButtonRepeat() { PopItemFlag(); } 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.TextWrapPosStack.pop_back(); window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); } // FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32 void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col) { ImGuiContext& g = *GImGui; ImGuiColMod backup; backup.Col = idx; backup.BackupValue = g.Style.Colors[idx]; g.ColorModifiers.push_back(backup); g.Style.Colors[idx] = ColorConvertU32ToFloat4(col); } void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) { ImGuiContext& g = *GImGui; ImGuiColMod backup; backup.Col = idx; backup.BackupValue = g.Style.Colors[idx]; g.ColorModifiers.push_back(backup); g.Style.Colors[idx] = col; } void ImGui::PopStyleColor(int count) { ImGuiContext& g = *GImGui; while (count > 0) { ImGuiColMod& backup = g.ColorModifiers.back(); g.Style.Colors[backup.Col] = backup.BackupValue; g.ColorModifiers.pop_back(); count--; } } struct ImGuiStyleVarInfo { ImGuiDataType Type; ImU32 Offset; void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); } }; static const ImGuiStyleVarInfo GStyleVarInfo[] = { { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign }; static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx) { IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_); IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_Count_); return &GStyleVarInfo[idx]; } void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->Type == ImGuiDataType_Float) { ImGuiContext& g = *GImGui; float* pvar = (float*)var_info->GetVarPtr(&g.Style); g.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) { const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->Type == ImGuiDataType_Float2) { ImGuiContext& g = *GImGui; ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); g.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) { ImGuiContext& g = *GImGui; while (count > 0) { ImGuiStyleMod& backup = g.StyleModifiers.back(); const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr(&g.Style)) = backup.BackupFloat[0]; else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr(&g.Style)) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]); else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr(&g.Style)) = backup.BackupInt[0]; g.StyleModifiers.pop_back(); count--; } } const char* ImGui::GetStyleColorName(ImGuiCol idx) { // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; switch (idx) { case ImGuiCol_Text: return "Text"; case ImGuiCol_TextDisabled: return "TextDisabled"; case ImGuiCol_WindowBg: return "WindowBg"; case ImGuiCol_ChildBg: return "ChildBg"; case ImGuiCol_PopupBg: return "PopupBg"; case ImGuiCol_Border: return "Border"; case ImGuiCol_BorderShadow: return "BorderShadow"; case ImGuiCol_FrameBg: return "FrameBg"; case ImGuiCol_FrameBgHovered: return "FrameBgHovered"; case ImGuiCol_FrameBgActive: return "FrameBgActive"; case ImGuiCol_TitleBg: return "TitleBg"; case ImGuiCol_TitleBgActive: return "TitleBgActive"; case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; case ImGuiCol_MenuBarBg: return "MenuBarBg"; case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; case ImGuiCol_CheckMark: return "CheckMark"; case ImGuiCol_SliderGrab: return "SliderGrab"; case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; case ImGuiCol_Button: return "Button"; case ImGuiCol_ButtonHovered: return "ButtonHovered"; case ImGuiCol_ButtonActive: return "ButtonActive"; case ImGuiCol_Header: return "Header"; case ImGuiCol_HeaderHovered: return "HeaderHovered"; case ImGuiCol_HeaderActive: return "HeaderActive"; case ImGuiCol_Separator: return "Separator"; case ImGuiCol_SeparatorHovered: return "SeparatorHovered"; case ImGuiCol_SeparatorActive: return "SeparatorActive"; case ImGuiCol_ResizeGrip: return "ResizeGrip"; case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; case ImGuiCol_CloseButton: return "CloseButton"; case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered"; case ImGuiCol_CloseButtonActive: return "CloseButtonActive"; case ImGuiCol_PlotLines: return "PlotLines"; case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; case ImGuiCol_PlotHistogram: return "PlotHistogram"; case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening"; case ImGuiCol_DragDropTarget: return "DragDropTarget"; case ImGuiCol_NavHighlight: return "NavHighlight"; case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; } IM_ASSERT(0); return "Unknown"; } bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent) { if (window->RootWindow == potential_parent) return true; while (window != NULL) { if (window == potential_parent) return true; window = window->ParentWindow; } return false; } bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) { IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function ImGuiContext& g = *GImGui; if (flags & ImGuiHoveredFlags_AnyWindow) { if (g.HoveredWindow == NULL) return false; } else { switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) { case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows: if (g.HoveredRootWindow != g.CurrentWindow->RootWindow) return false; break; case ImGuiHoveredFlags_RootWindow: if (g.HoveredWindow != g.CurrentWindow->RootWindow) return false; break; case ImGuiHoveredFlags_ChildWindows: if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow)) return false; break; default: if (g.HoveredWindow != g.CurrentWindow) return false; break; } } if (!IsWindowContentHoverable(g.HoveredRootWindow, flags)) return false; if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId) return false; return true; } bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) { ImGuiContext& g = *GImGui; IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End() if (flags & ImGuiFocusedFlags_AnyWindow) return g.NavWindow != NULL; switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows)) { case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows: return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow; case ImGuiFocusedFlags_RootWindow: return g.NavWindow == g.CurrentWindow->RootWindow; case ImGuiFocusedFlags_ChildWindows: return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow); default: return g.NavWindow == g.CurrentWindow; } } // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) { ImGuiContext& g = *GImGui; return window->Active && window == window->RootWindowForTabbing && (!(window->Flags & ImGuiWindowFlags_NoNavFocus) || window == g.NavWindow); } float ImGui::GetWindowWidth() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.x; } float ImGui::GetWindowHeight() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.y; } ImVec2 ImGui::GetWindowPos() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; return window->Pos; } static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x) { window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it. window->Scroll.x = new_scroll_x; window->DC.CursorMaxPos.x -= window->Scroll.x; } static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) { window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it. window->Scroll.y = new_scroll_y; window->DC.CursorMaxPos.y -= window->Scroll.y; } static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowPosAllowFlags & cond) == 0) return; window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX); // Set const ImVec2 old_pos = window->Pos; window->PosFloat = pos; window->Pos = ImFloor(pos); window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected. } void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond) { ImGuiWindow* window = GetCurrentWindowRead(); SetWindowPos(window, pos, cond); } void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowPos(window, pos, cond); } ImVec2 ImGui::GetWindowSize() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Size; } static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) return; window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); // Set 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->AutoFitFramesY = 0; window->SizeFull.y = size.y; } else { window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } } void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond) { SetWindowSize(GImGui->CurrentWindow, size, cond); } void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowSize(window, size, cond); } static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) return; window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); // Set window->Collapsed = collapsed; } void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond) { SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); } bool ImGui::IsWindowCollapsed() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Collapsed; } bool ImGui::IsWindowAppearing() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Appearing; } void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowCollapsed(window, collapsed, cond); } void ImGui::SetWindowFocus() { FocusWindow(GImGui->CurrentWindow); } void ImGui::SetWindowFocus(const char* name) { if (name) { if (ImGuiWindow* window = FindWindowByName(name)) FocusWindow(window); } else { FocusWindow(NULL); } } void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot) { ImGuiContext& g = *GImGui; g.NextWindowData.PosVal = pos; g.NextWindowData.PosPivotVal = pivot; g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always; } void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond) { ImGuiContext& g = *GImGui; g.NextWindowData.SizeVal = size; g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always; } void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data) { ImGuiContext& g = *GImGui; g.NextWindowData.SizeConstraintCond = ImGuiCond_Always; g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max); g.NextWindowData.SizeCallback = custom_callback; g.NextWindowData.SizeCallbackUserData = custom_callback_user_data; } void ImGui::SetNextWindowContentSize(const ImVec2& size) { ImGuiContext& g = *GImGui; g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value. g.NextWindowData.ContentSizeCond = ImGuiCond_Always; } void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) { ImGuiContext& g = *GImGui; g.NextWindowData.CollapsedVal = collapsed; g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always; } void ImGui::SetNextWindowFocus() { ImGuiContext& g = *GImGui; g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op) } void ImGui::SetNextWindowBgAlpha(float alpha) { ImGuiContext& g = *GImGui; g.NextWindowData.BgAlphaVal = alpha; g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op) } // In window space (not screen space!) ImVec2 ImGui::GetContentRegionMax() { ImGuiWindow* window = GetCurrentWindowRead(); ImVec2 mx = window->ContentsRegionRect.Max; if (window->DC.ColumnsSet) mx.x = GetColumnOffset(window->DC.ColumnsSet->Current + 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 = GetCurrentWindowRead(); return window->ContentsRegionRect.Min; } ImVec2 ImGui::GetWindowContentRegionMax() { 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() { ImGuiContext& g = *GImGui; return g.FontSize; } float ImGui::GetTextLineHeightWithSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.ItemSpacing.y; } float ImGui::GetFrameHeight() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.FramePadding.y * 2.0f; } float ImGui::GetFrameHeightWithSpacing() { 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::GetFont() { return GImGui->Font; } float ImGui::GetFontSize() { return GImGui->FontSize; } ImVec2 ImGui::GetFontTexUvWhitePixel() { return GImGui->DrawListSharedData.TexUvWhitePixel; } void ImGui::SetWindowFontScale(float scale) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } // 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 = GetCurrentWindowRead(); return window->DC.CursorPos - window->Pos + window->Scroll; } float ImGui::GetCursorPosX() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; } float ImGui::GetCursorPosY() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; } void ImGui::SetCursorPos(const ImVec2& local_pos) { ImGuiWindow* window = GetCurrentWindow(); 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 - 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 - 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 = GetCurrentWindowRead(); return window->DC.CursorPos; } 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::GetScrollX() { return GImGui->CurrentWindow->Scroll.x; } float ImGui::GetScrollY() { return GImGui->CurrentWindow->Scroll.y; } float ImGui::GetScrollMaxX() { return GetScrollMaxX(GImGui->CurrentWindow); } float ImGui::GetScrollMaxY() { return GetScrollMaxY(GImGui->CurrentWindow); } 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(); IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y); window->ScrollTargetCenterRatio.y = center_y_ratio; // Minor hack to to make scrolling to top/bottom of window take account of WindowPadding, it looks more right to the user this way if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) window->ScrollTarget.y = 0.0f; else if (center_y_ratio >= 1.0f && window->ScrollTarget.y >= window->SizeContents.y - window->WindowPadding.y + GImGui->Style.ItemSpacing.y) window->ScrollTarget.y = window->SizeContents.y; } // 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(); float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space target_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, center_y_ratio); } void ImGui::ActivateItem(ImGuiID id) { ImGuiContext& g = *GImGui; g.NavNextActivateId = id; } void ImGui::SetKeyboardFocusHere(int offset) { IM_ASSERT(offset >= -1); // -1 is allowed but not below ImGuiWindow* window = GetCurrentWindow(); window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; window->FocusIdxTabRequestNext = INT_MAX; } void ImGui::SetItemDefaultFocus() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!window->Appearing) return; if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent) { g.NavInitRequest = false; g.NavInitResultId = g.NavWindow->DC.LastItemId; g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos); NavUpdateAnyRequestFlag(); if (!IsItemVisible()) SetScrollHere(); } } void ImGui::SetStateStorage(ImGuiStorage* tree) { ImGuiWindow* window = GetCurrentWindow(); window->DC.StateStorage = tree ? tree : &window->StateStorage; } ImGuiStorage* ImGui::GetStateStorage() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.StateStorage; } void ImGui::TextV(const char* fmt, va_list args) { 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); } void ImGui::Text(const char* fmt, ...) { va_list args; va_start(args, fmt); TextV(fmt, args); va_end(args); } void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) { PushStyleColor(ImGuiCol_Text, col); TextV(fmt, args); PopStyleColor(); } void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) { va_list args; va_start(args, fmt); TextColoredV(col, fmt, args); 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) { 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); if (need_wrap) PopTextWrapPos(); } void ImGui::TextWrapped(const char* fmt, ...) { va_list args; va_start(args, fmt); TextWrappedV(fmt, args); va_end(args); } void ImGui::TextUnformatted(const char* text, const char* text_end) { 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 ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset); 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. // 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 = GetTextLineHeight(); const ImRect clip_rect = window->ClipRect; ImVec2 text_size(0,0); 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.Min.y - text_pos.y) / line_height); if (lines_skippable > 0) { int lines_skipped = 0; 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++; } pos.y += lines_skipped * line_height; } } // Lines to render if (line < text_end) { ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); while (line < text_end) { const char* line_end = strchr(line, '\n'); if (IsClippedEx(line_rect, 0, false)) break; const ImVec2 line_size = CalcTextSize(line, line_end, false); text_size.x = ImMax(text_size.x, line_size.x); RenderText(pos, line, line_end, false); if (!line_end) line_end = text_end; line = line_end + 1; line_rect.Min.y += line_height; line_rect.Max.y += line_height; pos.y += line_height; } // Count remaining lines int lines_skipped = 0; while (line < text_end) { const char* line_end = strchr(line, '\n'); if (!line_end) line_end = text_end; line = line_end + 1; lines_skipped++; } pos.y += lines_skipped * line_height; } text_size.y += (pos - text_pos).y; } ImRect bb(text_pos, text_pos + text_size); ItemSize(bb); ItemAdd(bb, 0); } else { const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); // Account of baseline offset ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size); if (!ItemAdd(bb, 0)) return; // Render (we don't hide text after ## in this end-user function) RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); } } void ImGui::AlignTextToFramePadding() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; window->DC.CurrentLineHeight = ImMax(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y * 2); window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); } // Add a label+text combo aligned to other label+value widgets void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); 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, 0)) return; // Render 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, ...) { va_list args; va_start(args, fmt); LabelTextV(label, fmt, args); va_end(args); } bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (flags & ImGuiButtonFlags_Disabled) { if (out_hovered) *out_hovered = false; if (out_held) *out_held = false; if (g.ActiveId == id) ClearActiveID(); return false; } // Default behavior requires click+release on same spot if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0) flags |= ImGuiButtonFlags_PressedOnClickRelease; ImGuiWindow* backup_hovered_window = g.HoveredWindow; if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window) g.HoveredWindow = window; bool pressed = false; bool hovered = ItemHoverable(bb, id); // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button if ((flags & ImGuiButtonFlags_PressedOnDragDropHold) && g.DragDropActive && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers)) if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { hovered = true; SetHoveredID(id); if (CalcTypematicPressedRepeatAmount(g.HoveredIdTimer + 0.0001f, g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, 0.01f, 0.70f)) // FIXME: Our formula for CalcTypematicPressedRepeatAmount() is fishy { pressed = true; FocusWindow(window); } } if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window) g.HoveredWindow = backup_hovered_window; // 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_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0)) hovered = false; // Mouse if (hovered) { if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) { // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat // PressedOnClickRelease | * | .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds // PressedOnClick | | .. // PressedOnRelease | | .. (NOT on release) // PressedOnDoubleClick | | .. // FIXME-NAV: We don't honor those different behaviors. if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) { SetActiveID(id, window); if (!(flags & ImGuiButtonFlags_NoNavFocus)) SetFocusID(id, window); FocusWindow(window); } if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0])) { pressed = true; if (flags & ImGuiButtonFlags_NoHoldingActiveID) ClearActiveID(); else SetActiveID(id, window); // Hold on ID FocusWindow(window); } if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0]) { if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps pressed = true; ClearActiveID(); } // '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; } if (pressed) g.NavDisableHighlight = true; } // Gamepad/Keyboard navigation // We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse. if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId)) hovered = true; if (g.NavActivateDownId == id) { bool nav_activated_by_code = (g.NavActivateId == id); bool nav_activated_by_inputs = IsNavInputPressed(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed); if (nav_activated_by_code || nav_activated_by_inputs) pressed = true; if (nav_activated_by_code || nav_activated_by_inputs || g.ActiveId == id) { // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button. g.NavActivateId = id; // This is so SetActiveId assign a Nav source SetActiveID(id, window); if (!(flags & ImGuiButtonFlags_NoNavFocus)) SetFocusID(id, window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right) | (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); } } bool held = false; if (g.ActiveId == id) { if (g.ActiveIdSource == ImGuiInputSource_Mouse) { if (g.ActiveIdIsJustActivated) g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; if (g.IO.MouseDown[0]) { held = true; } else { if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease)) if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps if (!g.DragDropActive) pressed = true; ClearActiveID(); } if (!(flags & ImGuiButtonFlags_NoNavFocus)) g.NavDisableHighlight = true; } else if (g.ActiveIdSource == ImGuiInputSource_Nav) { if (g.NavActivateDownId != id) ClearActiveID(); } } if (out_hovered) *out_hovered = hovered; if (out_held) *out_held = held; return pressed; } bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { 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); 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.ItemFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavHighlight(bb, id); 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); // Automatically close popups //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); return pressed; } bool ImGui::Button(const char* label, const ImVec2& size_arg) { 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_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); return pressed; } // Button to close a window bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window. // (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible). const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius)); bool is_clipped = !ItemAdd(bb, id); bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); if (is_clipped) return pressed; // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); ImVec2 center = bb.GetCenter(); window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12); const float cross_extent = (radius * 0.7071f) - 1.0f; if (hovered) { center -= ImVec2(0.5f, 0.5f); 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)); } return pressed; } // [Internal] bool ImGui::ArrowButton(ImGuiID id, ImGuiDir dir, ImVec2 padding, ImGuiButtonFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + padding.x * 2.0f, g.FontSize + padding.y * 2.0f)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderTriangle(bb.Min + padding, dir, 1.0f); return pressed; } void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); if (border_col.w > 0.0f) bb.Max += ImVec2(2,2); ItemSize(bb); if (!ItemAdd(bb, 0)) return; if (border_col.w > 0.0f) { 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, GetColorU32(tint_col)); } } // frame_padding < 0: uses FramePadding from style (default) // frame_padding = 0: no framing // frame_padding > 0: set framing size // 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) { 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 UV. PushID((void *)user_texture_id); const ImGuiID id = window->GetID("#image"); 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); ItemSize(bb); if (!ItemAdd(bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavHighlight(bb, id); 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, GetColorU32(bg_col)); window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); return pressed; } // Start logging ImGui output to TTY void ImGui::LogToTTY(int max_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(g.LogFile == NULL); g.LogFile = stdout; g.LogEnabled = true; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } // Start logging ImGui output to given file void ImGui::LogToFile(int max_depth, const char* filename) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; ImGuiWindow* window = g.CurrentWindow; if (!filename) { filename = g.IO.LogFilename; if (!filename) return; } IM_ASSERT(g.LogFile == NULL); g.LogFile = ImFileOpen(filename, "ab"); if (!g.LogFile) { IM_ASSERT(g.LogFile != NULL); // Consider this an error return; } g.LogEnabled = true; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } // Start logging ImGui output to clipboard void ImGui::LogToClipboard(int max_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(g.LogFile == NULL); g.LogFile = NULL; g.LogEnabled = true; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } void ImGui::LogFinish() { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; LogText(IM_NEWLINE); if (g.LogFile != NULL) { if (g.LogFile == stdout) fflush(g.LogFile); else fclose(g.LogFile); g.LogFile = NULL; } if (g.LogClipboard->size() > 1) { SetClipboardText(g.LogClipboard->begin()); g.LogClipboard->clear(); } g.LogEnabled = false; } // Helper to display logging buttons void ImGui::LogButtons() { 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) LogToTTY(g.LogAutoExpandMaxDepth); if (log_to_file) LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename); if (log_to_clipboard) LogToClipboard(g.LogAutoExpandMaxDepth); } bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) { 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 is_open; if (g.NextTreeNodeOpenCond != 0) { if (g.NextTreeNodeOpenCond & ImGuiCond_Always) { is_open = g.NextTreeNodeOpenVal; storage->SetInt(id, is_open); } else { // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently. const int stored_value = storage->GetInt(id, -1); if (stored_value == -1) { is_open = g.NextTreeNodeOpenVal; storage->SetInt(id, is_open); } else { is_open = stored_value != 0; } } g.NextTreeNodeOpenCond = 0; } else { is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; } // 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 || (flags & ImGuiTreeNodeFlags_FramePadding)) ? 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(padding.y, window->DC.CurrentLineTextBaseOffset); // 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 frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height)); if (display_frame) { // Framed header expand a little outside the default padding frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1; frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1; } 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); // 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 if we want the hit test to be done up to the right side of the content or not) const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x*2, frame_bb.Max.y); bool is_open = TreeNodeBehaviorIsOpen(id, flags); // Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child. // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). // This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero. if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavCloseFromChild) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) window->DC.TreeDepthMayCloseOnPop |= (1 << window->DC.TreeDepth); bool item_add = ItemAdd(interact_bb, id); window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; window->DC.LastItemDisplayRect = frame_bb; if (!item_add) { if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushRawID(id); return is_open; } // 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_AllowItemOverlap) ? ImGuiButtonFlags_AllowItemOverlap : 0); if (!(flags & ImGuiTreeNodeFlags_Leaf)) button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; 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 (!(flags & ImGuiTreeNodeFlags_Leaf)) { bool toggled = false; if (pressed) { toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id); if (flags & ImGuiTreeNodeFlags_OpenOnArrow) toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)) && (!g.NavDisableMouseHover); if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) toggled |= g.IO.MouseDoubleClicked[0]; if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again. toggled = false; } if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open) { toggled = true; NavMoveRequestCancel(); } if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority? { toggled = true; NavMoveRequestCancel(); } if (toggled) { is_open = !is_open; window->DC.StateStorage->SetInt(id, is_open); } } if (flags & ImGuiTreeNodeFlags_AllowItemOverlap) SetItemAllowOverlap(); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y); if (display_frame) { // Framed type RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding); RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin); RenderTriangle(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f); 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##"; const char log_suffix[] = "##"; LogRenderedText(&text_pos, log_prefix, log_prefix+3); RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); LogRenderedText(&text_pos, log_suffix+1, log_suffix+3); } else { RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); } } else { // Unframed typed for tree nodes if (hovered || (flags & ImGuiTreeNodeFlags_Selected)) { RenderFrame(frame_bb.Min, frame_bb.Max, col, false); RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin); } if (flags & ImGuiTreeNodeFlags_Bullet) RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y)); else if (!(flags & ImGuiTreeNodeFlags_Leaf)) RenderTriangle(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f); if (g.LogEnabled) LogRenderedText(&text_pos, ">"); RenderText(text_pos, label, label_end, false); } if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushRawID(id); return is_open; } // 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) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label); } bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; if (p_open && !*p_open) return false; ImGuiID id = window->GetID(label); bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap : 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; ImGuiItemHoveredDataBackup last_item_backup; 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; last_item_backup.Restore(); } return is_open; } bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), flags, label, NULL); } bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { 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); } bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { 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(ptr_id), flags, g.TempBuffer, label_end); } bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) { return TreeNodeExV(str_id, 0, fmt, args); } bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) { return TreeNodeExV(ptr_id, 0, fmt, args); } bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(str_id, flags, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) { 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, ImGuiCond cond) { ImGuiContext& g = *GImGui; if (g.CurrentWindow->SkipItems) return; g.NextTreeNodeOpenVal = is_open; g.NextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always; } void ImGui::PushID(const char* str_id) { ImGuiWindow* window = GetCurrentWindowRead(); window->IDStack.push_back(window->GetID(str_id)); } void ImGui::PushID(const char* str_id_begin, const char* str_id_end) { ImGuiWindow* window = GetCurrentWindowRead(); window->IDStack.push_back(window->GetID(str_id_begin, str_id_end)); } void ImGui::PushID(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindowRead(); window->IDStack.push_back(window->GetID(ptr_id)); } void ImGui::PushID(int int_id) { const void* ptr_id = (void*)(intptr_t)int_id; ImGuiWindow* window = GetCurrentWindowRead(); window->IDStack.push_back(window->GetID(ptr_id)); } void ImGui::PopID() { ImGuiWindow* window = GetCurrentWindowRead(); window->IDStack.pop_back(); } ImGuiID ImGui::GetID(const char* 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, 0)) { 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(); 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, 0)) 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. 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++; // We don't support '-' op because it would conflict with inputing negative value. // Instead you can use +-100 to subtract from an existing value char op = buf[0]; if (op == '+' || op == '*' || op == '/') { buf++; while (ImCharIsSpace(*buf)) buf++; } else { op = 0; } if (!buf[0]) return false; if (data_type == ImGuiDataType_Int) { if (!scalar_format) scalar_format = "%d"; int* v = (int*)data_ptr; const int old_v = *v; int arg0i = *v; if (op && sscanf(initial_value_buf, scalar_format, &arg0i) < 1) return false; // 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 arg1f = 0.0f; if (op == '+') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i + arg1f); } // Add (use "+-" to subtract) else if (op == '*') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i * arg1f); } // Multiply else if (op == '/') { if (sscanf(buf, "%f", &arg1f) == 1 && arg1f != 0.0f) *v = (int)(arg0i / arg1f); }// Divide else { if (sscanf(buf, scalar_format, &arg0i) == 1) *v = arg0i; } // Assign constant (read as integer so big values are not lossy) 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 arg0f = *v; if (op && sscanf(initial_value_buf, scalar_format, &arg0f) < 1) return false; float arg1f = 0.0f; if (sscanf(buf, scalar_format, &arg1f) < 1) return false; if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract) else if (op == '*') { *v = arg0f * arg1f; } // Multiply else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide else { *v = arg1f; } // Assign constant return (old_v != *v); } return false; } // Create text input in place of a slider (when CTRL+Clicking on slider) // FIXME: Logic is messy and confusing. bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen) // On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id SetActiveID(g.ScalarAsInputTextId, window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); SetHoveredID(0); FocusableItemUnregister(window); 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 we started displaying the InputText widget { 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; SetHoveredID(id); } 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 int ImGui::ParseFormatPrecision(const char* fmt, int default_precision) { int precision = default_precision; while ((fmt = strchr(fmt, '%')) != NULL) { fmt++; if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%" while (*fmt >= '0' && *fmt <= '9') fmt++; if (*fmt == '.') { fmt = ImAtoi(fmt + 1, &precision); if (precision < 0 || precision > 10) precision = default_precision; } if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation precision = -1; break; } return precision; } static float GetMinimumStepAtDecimalPrecision(int decimal_precision) { 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 }; return (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_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 if (decimal_precision < 0) return value; const float min_step = GetMinimumStepAtDecimalPrecision(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 inline float SliderBehaviorCalcRatioFromValue(float v, float v_min, float v_max, float power, float linear_zero_pos) { if (v_min == v_max) return 0.0f; const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f); const float v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_non_linear) { if (v_clamped < 0.0f) { const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min); return (1.0f - powf(f, 1.0f/power)) * linear_zero_pos; } else { const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min)); return linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos); } } // Linear slider return (v_clamped - v_min) / (v_max - v_min); } bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = g.Style; // Draw frame const ImU32 frame_col = GetColorU32((g.ActiveId == id && g.ActiveIdSource == ImGuiInputSource_Nav) ? ImGuiCol_FrameBgActive : ImGuiCol_FrameBg); RenderNavHighlight(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f); const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0; 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_min < v_max ? v_max - v_min : v_min - v_max) + 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 = (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 if (v_min * v_max < 0.0f) { // Different sign const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power); const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power); linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0); } else { // Same sign linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; } // Process interacting with the slider bool value_changed = false; if (g.ActiveId == id) { bool set_new_value = false; float clicked_t = 0.0f; if (g.ActiveIdSource == ImGuiInputSource_Mouse) { if (!g.IO.MouseDown[0]) { ClearActiveID(); } else { const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f; if (!is_horizontal) clicked_t = 1.0f - clicked_t; set_new_value = true; } } else if (g.ActiveIdSource == ImGuiInputSource_Nav) { const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f); float delta = is_horizontal ? delta2.x : -delta2.y; if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) { ClearActiveID(); } else if (delta != 0.0f) { clicked_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos); if (decimal_precision == 0 && !is_non_linear) { if (fabsf(v_max - v_min) <= 100.0f || IsNavInputDown(ImGuiNavInput_TweakSlow)) delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (v_max - v_min); // Gamepad/keyboard tweak speeds in integer steps else delta /= 100.0f; } else { delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds if (IsNavInputDown(ImGuiNavInput_TweakSlow)) delta /= 10.0f; } if (IsNavInputDown(ImGuiNavInput_TweakFast)) delta *= 10.0f; set_new_value = true; if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits set_new_value = false; else clicked_t = ImSaturate(clicked_t + delta); } } if (set_new_value) { float new_value; if (is_non_linear) { // Account for logarithmic scale on both sides of the zero if (clicked_t < linear_zero_pos) { // Negative: rescale to the negative range before powering float a = 1.0f - (clicked_t / linear_zero_pos); a = powf(a, power); 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-6f) a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos); else a = clicked_t; a = powf(a, power); new_value = ImLerp(ImMax(v_min,0.0f), v_max, a); } } else { // Linear slider new_value = ImLerp(v_min, v_max, clicked_t); } // Round past decimal precision new_value = RoundScalar(new_value, decimal_precision); if (*v != new_value) { *v = new_value; value_changed = true; } } } // Draw float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos); 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 (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 + 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; } // Use power!=1.0 for logarithmic sliders. // Adjust display_format to decorate the value with a prefix or a suffix. // "%.3f" 1.234 // "%5.2f secs" 01.23 secs // "Gold: %.0f" Gold: 1 bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power) { 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 = 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.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 if (!ItemAdd(total_bb, id, &frame_bb)) { ItemSize(total_bb, style.FramePadding.y); return false; } const bool hovered = ItemHoverable(frame_bb, id); if (!display_format) display_format = "%.3f"; 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 = FocusableItemRegister(window, id); if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) { SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); if (tab_focus_requested || g.IO.KeyCtrl || g.NavInputId == id) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); // Actual slider behavior + render grab ItemSize(total_bb, style.FramePadding.y); 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); 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, 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) { 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 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); if (!ItemAdd(frame_bb, id)) return false; const bool hovered = ItemHoverable(frame_bb, id); if (!display_format) display_format = "%.3f"; int decimal_precision = ParseFormatPrecision(display_format, 3); if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id) { SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); } // Actual slider behavior + render grab 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); 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, 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*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; } bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; 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 bool ImGui::SliderFloatN(const char* label, float* v, int components, 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 |= SliderFloat("##v", &v[i], 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::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 2, v_min, v_max, display_format, power); } bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 3, v_min, v_max, display_format, power); } bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 4, v_min, v_max, display_format, power); } bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format) { 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 |= SliderInt("##v", &v[i], 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::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 2, v_min, v_max, display_format); } bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 3, v_min, v_max, display_format); } bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 4, v_min, v_max, display_format); } 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) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavHighlight(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); bool value_changed = false; // Process interacting with the drag if (g.ActiveId == id) { if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0]) ClearActiveID(); else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) ClearActiveID(); } if (g.ActiveId == id) { if (g.ActiveIdIsJustActivated) { // Lock current value on click g.DragCurrentValue = *v; g.DragLastMouseDelta = ImVec2(0.f, 0.f); } if (v_speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX) v_speed = (v_max - v_min) * g.DragSpeedDefaultRatio; float v_cur = g.DragCurrentValue; const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f); float adjust_delta = 0.0f; if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid()) { adjust_delta = mouse_drag_delta.x - g.DragLastMouseDelta.x; if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f) adjust_delta *= g.DragSpeedScaleFast; if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f) adjust_delta *= g.DragSpeedScaleSlow; g.DragLastMouseDelta.x = mouse_drag_delta.x; } if (g.ActiveIdSource == ImGuiInputSource_Nav) { adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard|ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f/10.0f, 10.0f).x; if (v_min < v_max && ((v_cur >= v_max && adjust_delta > 0.0f) || (v_cur <= v_min && adjust_delta < 0.0f))) // This is to avoid applying the saturation when already past the limits adjust_delta = 0.0f; v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision)); } adjust_delta *= v_speed; if (fabsf(adjust_delta) > 0.0f) { 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) + (adjust_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 += adjust_delta; } // Clamp if (v_min < v_max) v_cur = ImClamp(v_cur, v_min, v_max); g.DragCurrentValue = v_cur; } // Round to user desired precision, then apply v_cur = RoundScalar(v_cur, decimal_precision); if (*v != v_cur) { *v = v_cur; value_changed = true; } } return value_changed; } bool ImGui::DragFloat(const char* label, float* v, 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; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); 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.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)); // NB- we don't call ItemSize() yet because we may turn into a text edit box below if (!ItemAdd(total_bb, id, &frame_bb)) { ItemSize(total_bb, style.FramePadding.y); return false; } const bool hovered = ItemHoverable(frame_bb, id); if (!display_format) display_format = "%.3f"; 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 = FocusableItemRegister(window, id); if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) { SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); // Actual drag behavior 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); 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); return value_changed; } 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 = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format); *v = (int)v_f; return value_changed; } bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format) { 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(); 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) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImVec2 label_size = CalcTextSize(label, NULL, true); if (graph_size.x == 0.0f) graph_size.x = CalcItemWidth(); if (graph_size.y == 0.0f) graph_size.y = label_size.y + (style.FramePadding.y * 2); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); 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)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, 0, &frame_bb)) return; const bool hovered = ItemHoverable(inner_bb, 0); // Determine scale from values if not specified if (scale_min == FLT_MAX || scale_max == FLT_MAX) { float v_min = FLT_MAX; float v_max = -FLT_MAX; for (int i = 0; i < values_count; i++) { const float v = values_getter(data, i); v_min = ImMin(v_min, v); v_max = ImMax(v_max, v); } if (scale_min == FLT_MAX) scale_min = v_min; if (scale_max == FLT_MAX) scale_max = v_max; } RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); if (values_count > 0) { 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 (hovered) { 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 * 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) SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); else if (plot_type == ImGuiPlotType_Histogram) SetTooltip("%d: %8.4g", v_idx, v0); v_hovered = v_idx; } const float t_step = 1.0f / (float)res_w; const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min)); float v0 = values_getter(data, (0 + values_offset) % values_count); float t0 = 0.0f; ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands 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 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) * inv_scale) ); // 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, histogram_zero_line_t)); if (plot_type == ImGuiPlotType_Lines) { window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); } else if (plot_type == ImGuiPlotType_Histogram) { 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; tp0 = tp1; } } // Text overlay if (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)); 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; int Stride; ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } }; static float Plot_ArrayGetter(void* data, int idx) { ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); 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, int stride) { ImGuiPlotArrayGetterData data(values, stride); 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) { 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, int stride) { ImGuiPlotArrayGetterData data(values, stride); 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) { 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, 0)) return; // Render fraction = ImSaturate(fraction); RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize)); const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y); RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, 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) { 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 check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2)); // We want a square shape to we use Y twice ItemSize(check_bb, style.FramePadding.y); ImRect total_bb = check_bb; if (label_size.x > 0) 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) { ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); } if (!ItemAdd(total_bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) *v = !(*v); RenderNavHighlight(total_bb, id); 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 = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); RenderCheckMark(check_bb.Min + ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), check_bb.GetWidth() - pad*2.0f); } if (g.LogEnabled) LogRenderedText(&text_bb.Min, *v ? "[x]" : "[ ]"); if (label_size.x > 0.0f) RenderText(text_bb.Min, label); return pressed; } bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int 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) { 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 check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1)); ItemSize(check_bb, style.FramePadding.y); ImRect total_bb = check_bb; if (label_size.x > 0) 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) { ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); total_bb.Add(text_bb); } if (!ItemAdd(total_bb, id)) return false; ImVec2 center = check_bb.GetCenter(); center.x = (float)(int)center.x + 0.5f; center.y = (float)(int)center.y + 0.5f; const float radius = check_bb.GetHeight() * 0.5f; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); RenderNavHighlight(total_bb, id); 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 = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16); } if (style.FrameBorderSize > 0.0f) { window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize); window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize); } if (g.LogEnabled) LogRenderedText(&text_bb.Min, active ? "(x)" : "( )"); if (label_size.x > 0.0f) RenderText(text_bb.Min, label); return pressed; } bool ImGui::RadioButton(const char* label, int* v, int v_button) { const bool pressed = RadioButton(label, *v == v_button); if (pressed) { *v = 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) 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) { 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 = 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 - (text + line_start_idx)); } 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) { 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) { 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) { 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.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.Data + pos + n; while (ImWchar c = *src++) *dst++ = c; *dst = '\0'; } static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) { 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 (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA) return false; 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; obj->Text[obj->CurLenW] = '\0'; return true; } // We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) #define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left #define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right #define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up #define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down #define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line #define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line #define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text #define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text #define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor #define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor #define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo #define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo #define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word #define STB_TEXTEDIT_K_SHIFT 0x20000 #define STB_TEXTEDIT_IMPLEMENTATION #include "stb_textedit.h" } void ImGuiTextEditState::OnKeyPressed(int key) { 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'; 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 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; 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'; if (CursorPos >= pos) CursorPos += new_text_len; SelectionStart = SelectionEnd = CursorPos; BufDirty = true; BufTextLen += new_text_len; } // Return false to discard a character. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { unsigned int c = *p_char; if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) { 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; if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank)) { if (flags & ImGuiInputTextFlags_CharsDecimal) if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) return false; if (flags & ImGuiInputTextFlags_CharsHexadecimal) if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return false; if (flags & ImGuiInputTextFlags_CharsUppercase) if (c >= 'a' && c <= 'z') *p_char = (c += (unsigned int)('A'-'a')); if (flags & ImGuiInputTextFlags_CharsNoBlank) if (ImCharIsSpace(c)) return false; } if (flags & ImGuiInputTextFlags_CallbackCharFilter) { ImGuiTextEditCallbackData callback_data; memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; callback_data.EventChar = (ImWchar)c; callback_data.Flags = flags; callback_data.UserData = user_data; if (callback(&callback_data) != 0) return false; *p_char = callback_data.EventChar; if (!callback_data.EventChar) return false; } return true; } // Edit a string of text // 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) { 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 bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0; const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 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); 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)); ImGuiWindow* draw_window = window; if (is_multiline) { ItemAdd(total_bb, id, &frame_bb); 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, &frame_bb)) return false; } const bool hovered = ItemHoverable(frame_bb, id); if (hovered) g.MouseCursor = ImGuiMouseCursor_TextInput; // Password pushes a temporary font with only a fallback glyph if (is_password) { const ImFontGlyph* 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->FallbackAdvanceX = glyph->AdvanceX; IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.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 focus_requested = FocusableItemRegister(window, 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 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 clear_active_id = false; bool select_all = (g.ActiveId != id) && (((flags & ImGuiInputTextFlags_AutoSelectAll) != 0) || (g.NavInputId == id)) && (!is_multiline); if (focus_requested || user_clicked || user_scrolled || g.NavInputId == id) { 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' (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.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(); // 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) { // 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 { 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 (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, window); SetFocusID(id, window); FocusWindow(window); if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory)) g.ActiveIdAllowNavDirFlags |= ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down)); } else if (io.MouseClicked[0]) { // Release focus when we click outside clear_active_id = true; } bool value_changed = false; bool enter_pressed = false; if (g.ActiveId == id) { 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; // 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]; g.WantTextInputNextFrame = 1; // Edit in progress 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)); const bool osx_double_click_selects_words = io.OptMacOSXBehaviors; // 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) { if (hovered) { stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y); edit_state.CursorAnimReset(); } } 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, mouse_x, mouse_y); edit_state.CursorAnimReset(); edit_state.CursorFollow = true; } if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) edit_state.SelectedAllMouseLock = false; if (io.InputCharacters[0]) { // Process text input (before we check for Return because using some IME will effectively send a Return?) // 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) { 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)); } } bool cancel_edit = false; if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id) { // Handle key-presses const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); const bool is_shortcut_key_only = (io.OptMacOSXBehaviors ? (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.OptMacOSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl const bool is_startend_key_down = io.OptMacOSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper; const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper; const bool is_cut = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && is_editable && !is_password && (!is_multiline || edit_state.HasSelection()); const bool is_copy = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || edit_state.HasSelection()); const bool is_paste = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && is_editable; 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.OptMacOSXBehaviors && 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)) { enter_pressed = clear_active_id = 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)) { clear_active_id = cancel_edit = true; } else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); } else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable && is_undoable) { 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_cut || is_copy) { // Cut, Copy 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) : 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); SetClipboardText(edit_state.TempTextBuffer.Data); } if (is_cut) { if (!edit_state.HasSelection()) edit_state.SelectAll(); edit_state.CursorFollow = true; stb_textedit_cut(&edit_state, &edit_state.StbState); } } else if (is_paste) { // Paste if (const char* clipboard = GetClipboardText()) { // 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; ) { 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); } } } if (g.ActiveId == id) { if (cancel_edit) { // Restore initial value if (is_editable) { ImStrncpy(buf, edit_state.InitialText.Data, buf_size); value_changed = true; } } // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame. // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. Also this allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage. bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0); if (apply_edit_back_to_user_buffer) { // Apply new value immediately - copy modified buffer back // 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) { IM_ASSERT(callback != NULL); // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. ImGuiInputTextFlags event_flag = 0; ImGuiKey event_key = ImGuiKey_COUNT; if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab)) { event_flag = ImGuiInputTextFlags_CallbackCompletion; event_key = ImGuiKey_Tab; } else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow)) { event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_UpArrow; } else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow)) { event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_DownArrow; } else if (flags & ImGuiInputTextFlags_CallbackAlways) event_flag = ImGuiInputTextFlags_CallbackAlways; if (event_flag) { ImGuiTextEditCallbackData callback_data; 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 = edit_state.TempTextBuffer.Data; callback_data.BufTextLen = edit_state.CurLenA; callback_data.BufSize = edit_state.BufSizeA; callback_data.BufDirty = false; // 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 == 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); if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); 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) { 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(); } } } // Copy back to user buffer if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0) { ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size); value_changed = true; } } } // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value) if (clear_active_id && g.ActiveId == id) ClearActiveID(); // 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; RenderNavHighlight(frame_bb, id); 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++; } // 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; } // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224) if (is_multiline) text_size = ImVec2(size.x, line_count * g.FontSize); } // 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; } // 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 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.ClipWith(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.IO.OptCursorBlink) || (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); } 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); if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) return enter_pressed; else return value_changed; } 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) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImVec2 label_size = CalcTextSize(label, NULL, true); BeginGroup(); PushID(label); const ImVec2 button_sz = ImVec2(GetFrameHeight(), GetFrameHeight()); 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; 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) { PopItemWidth(); 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; } 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; } } 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, IM_ARRAYSIZE(display_format), "%%.%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(); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags) { return InputFloatN(label, v, 2, decimal_precision, extra_flags); } bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags) { return InputFloatN(label, v, 3, decimal_precision, extra_flags); } bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags) { return InputFloatN(label, v, 4, decimal_precision, extra_flags); } bool ImGui::InputIntN(const char* label, int* v, int components, 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 |= InputInt("##v", &v[i], 0, 0, extra_flags); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags) { return InputIntN(label, v, 2, extra_flags); } bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags) { return InputIntN(label, v, 3, extra_flags); } bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags) { return InputIntN(label, v, 4, extra_flags); } static float CalcMaxPopupHeightFromItemCount(int items_count) { ImGuiContext& g = *GImGui; if (items_count <= 0) return FLT_MAX; return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2); } bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags) { // Always consume the SetNextWindowSizeConstraint() call in our early return paths ImGuiContext& g = *GImGui; ImGuiCond backup_next_window_size_constraint = g.NextWindowData.SizeConstraintCond; g.NextWindowData.SizeConstraintCond = 0; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); 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.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, &frame_bb)) return false; bool hovered, held; bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held); bool popup_open = IsPopupOpen(id); const float arrow_size = GetFrameHeight(); const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); RenderNavHighlight(frame_bb, id); 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 RenderTriangle(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down); if (preview_value != NULL) RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, preview_value, 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); if ((pressed || g.NavActivateId == id) && !popup_open) { if (window->DC.NavLayerCurrent == 0) window->NavLastIds[0] = id; OpenPopupEx(id); popup_open = true; } if (!popup_open) return false; if (backup_next_window_size_constraint) { g.NextWindowData.SizeConstraintCond = backup_next_window_size_constraint; g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w); } else { if ((flags & ImGuiComboFlags_HeightMask_) == 0) flags |= ImGuiComboFlags_HeightRegular; IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one int popup_max_height_in_items = -1; if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8; else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4; else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20; SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); } char name[16]; ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth // Peak into expected window size so we can position it if (ImGuiWindow* popup_window = FindWindowByName(name)) if (popup_window->WasActive) { ImVec2 size_contents = CalcSizeContents(popup_window); ImVec2 size_expected = CalcSizeAfterConstraint(popup_window, CalcSizeAutoFit(popup_window, size_contents)); if (flags & ImGuiComboFlags_PopupAlignLeft) popup_window->AutoPosLastDirection = ImGuiDir_Left; ImVec2 pos = FindBestWindowPosForPopup(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, frame_bb, ImGuiPopupPositionPolicy_ComboBox); SetNextWindowPos(pos); } ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings; if (!Begin(name, NULL, window_flags)) { EndPopup(); IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above return false; } // Horizontally align ourselves with the framed text if (style.FramePadding.x != style.WindowPadding.x) Indent(style.FramePadding.x - style.WindowPadding.x); return true; } void ImGui::EndCombo() { const ImGuiStyle& style = GImGui->Style; if (style.FramePadding.x != style.WindowPadding.x) Unindent(style.FramePadding.x - style.WindowPadding.x); EndPopup(); } // Old API, prefer using BeginCombo() nowadays if you can. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items) { ImGuiContext& g = *GImGui; const char* preview_text = NULL; if (*current_item >= 0 && *current_item < items_count) items_getter(data, *current_item, &preview_text); // The old Combo() API exposed "popup_max_height_in_items", however the new more general BeginCombo() API doesn't, so we emulate it here. if (popup_max_height_in_items != -1 && !g.NextWindowData.SizeConstraintCond) { float popup_max_height = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items); SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, popup_max_height)); } if (!BeginCombo(label, preview_text, 0)) return false; // Display items // FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed) bool value_changed = false; for (int i = 0; i < items_count; 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)) { value_changed = true; *current_item = i; } if (item_selected) SetItemDefaultFocus(); PopID(); } EndCombo(); return value_changed; } static bool Items_ArrayGetter(void* data, int idx, const char** out_text) { const char* const* items = (const char* const*)data; if (out_text) *out_text = items[idx]; return true; } static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) { // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited. const char* items_separated_by_zeros = (const char*)data; int items_count = 0; const char* p = items_separated_by_zeros; while (*p) { if (idx == items_count) break; p += strlen(p) + 1; items_count++; } if (!*p) return false; if (out_text) *out_text = p; return true; } // Combo box helper allowing to pass an array of strings. bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items) { const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); return value_changed; } // Combo box helper allowing to pass all items in a single string. 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, or at least only when combo is open while (*p) { p += strlen(p) + 1; items_count++; } bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); 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, ImGuiSelectableFlags flags, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) // FIXME-OPT: Avoid if vertically clipped. 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); // 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, (flags & ImGuiSelectableFlags_Disabled) ? 0 : id)) { if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) PushColumnClipRect(); return false; } ImGuiButtonFlags button_flags = 0; if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_NoHoldingActiveID; if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= 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, button_flags); if (flags & ImGuiSelectableFlags_Disabled) selected = false; // Hovering selectable with mouse updates NavId accordingly so navigation can be resumed with gamepad/keyboard (this doesn't happen on most widgets) if (pressed || hovered)// && (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)) if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerActiveMask) { g.NavDisableHighlight = true; SetNavID(id, window->DC.NavLayerCurrent); } // Render if (hovered || selected) { 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); RenderNavHighlight(bb_with_spacing, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding); } if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) { PushColumnClipRect(); bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x); } 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 && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup)) CloseCurrentPopup(); return pressed; } bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { if (Selectable(label, *p_selected, flags, size_arg)) { *p_selected = !*p_selected; return true; } return false; } // Helper to calculate the size of a listbox and display a label on the right. // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty" bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; 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 = 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; // Forward storage for ListBoxFooter.. dodgy. BeginGroup(); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); BeginChildFrame(id, frame_bb.GetSize()); return true; } bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items) { // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. // However we don't add +0.40f if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size. // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution. if (height_in_items < 0) height_in_items = ImMin(items_count, 7); float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f); // 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 = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y; return ListBoxHeader(label, size); } void ImGui::ListBoxFooter() { ImGuiWindow* parent_window = GetCurrentWindow()->ParentWindow; const ImRect bb = parent_window->DC.LastItemRect; 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 SameLine(); parent_window->DC.CursorPos = bb.Min; ItemSize(bb, style.FramePadding.y); EndGroup(); } bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items) { const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); return value_changed; } 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()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. 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; } if (item_selected) SetItemDefaultFocus(); 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; ImGuiStyle& style = g.Style; ImVec2 pos = window->DC.CursorPos; ImVec2 label_size = CalcTextSize(label, NULL, true); ImGuiSelectableFlags flags = ImGuiSelectableFlags_MenuItem | (enabled ? 0 : ImGuiSelectableFlags_Disabled); bool pressed; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful // Note that in this situation we render neither the shortcut neither the selected tick mark float w = label_size.x; window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); pressed = Selectable(label, false, flags, ImVec2(w, 0.0f)); PopStyleVar(); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). } else { 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); pressed = Selectable(label, false, flags | ImGuiSelectableFlags_DrawFillAvailWidth, 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.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled), g.FontSize * 0.866f); } 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(); // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window ImGuiContext& g = *GImGui; if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0) FocusFrontMostActiveWindow(g.NavWindow); 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"); // We don't clip with regular window clipping rectangle as it is already set to the area below. However we clip with window full rect. // We remove 1 worth of rounding to Max.x to that text in long menus don't tend to display over the lower-right rounded area, which looks particularly glitchy. ImRect bar_rect = window->MenuBarRect(); ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f)); clip_rect.ClipWith(window->WindowRectClipped); PushClipRect(clip_rect.Min, clip_rect.Max, false); window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffsetX, bar_rect.Min.y);// + g.Style.FramePadding.y); window->DC.LayoutType = ImGuiLayoutType_Horizontal; window->DC.NavLayerCurrent++; window->DC.NavLayerCurrentMask <<= 1; window->DC.MenuBarAppending = true; AlignTextToFramePadding(); return true; } void ImGui::EndMenuBar() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings. if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) { ImGuiWindow* nav_earliest_child = g.NavWindow; while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu)) nav_earliest_child = nav_earliest_child->ParentWindow; if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && g.NavMoveRequestForward == ImGuiNavForward_None) { // To do so we claim focus back, restore NavId and then process the movement request for yet another frame. // This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost) IM_ASSERT(window->DC.NavLayerActiveMaskNext & 0x02); // Sanity check FocusWindow(window); SetNavIDAndMoveMouse(window->NavLastIds[1], 1, window->NavRectRel[1]); g.NavLayer = 1; g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection. g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued; NavMoveRequestCancel(); } } 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.NavLayerCurrent--; window->DC.NavLayerCurrentMask >>= 1; window->DC.MenuBarAppending = false; } bool ImGui::BeginMenu(const char* label, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(label, NULL, true); 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].OpenParentId == window->IDStack.back()); ImGuiWindow* backed_nav_window = g.NavWindow; if (menuset_is_open) g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent) // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestPopupWindowPos). ImVec2 popup_pos, pos = window->DC.CursorPos; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { // Menu inside an horizontal menu bar // Selectable extend their highlight by half ItemSpacing in each direction. // For ChildMenu, the popup position will be overwritten by the call to FindBestPopupWindowPos() in Begin() 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(); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). } else { // Menu inside a menu 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]); RenderTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right); if (!enabled) PopStyleColor(); } const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id); if (menuset_is_open) g.NavWindow = backed_nav_window; bool want_open = false, want_close = false; if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (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 && !(window->Flags & ImGuiWindowFlags_MenuBar)) { 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 = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos); //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 } } 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); if (g.NavActivateId == id) { want_close = menu_is_open; want_open = !menu_is_open; } if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open { want_open = true; NavMoveRequestCancel(); } } else { // Menu bar if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it { want_close = true; want_open = menu_is_open = false; } else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others { want_open = true; } else if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open { want_open = true; NavMoveRequestCancel(); } } 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(g.CurrentPopupStack.Size); 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, ImGuiCond_Always); ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu); menu_is_open = BeginPopupEx(id, 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() { // Nav: When a left move request _within our child menu_ failed, close the menu. // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs. // However it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction. ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavWindow && g.NavWindow->ParentWindow == window && g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical) { ClosePopupToLevel(g.OpenPopupStack.Size - 1); NavMoveRequestCancel(); } EndPopup(); } // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags) { ImGuiContext& g = *GImGui; int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); BeginTooltipEx(0, true); const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text; if (text_end > text) { TextUnformatted(text, text_end); Separator(); } ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2); ColorButton("##preview", ImVec4(col[0], col[1], col[2], col[3]), (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz); SameLine(); if (flags & ImGuiColorEditFlags_NoAlpha) Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]); else Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]); EndTooltip(); } static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b) { float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f; int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t); int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t); int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t); return IM_COL32(r, g, b, 0xFF); } // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. // I spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether. void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags) { ImGuiWindow* window = GetCurrentWindow(); if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF) { ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col)); ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col)); window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags); int yi = 0; for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++) { float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y); if (y2 <= y1) continue; for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f) { float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x); if (x2 <= x1) continue; int rounding_corners_flags_cell = 0; if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopRight; } if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotRight; } rounding_corners_flags_cell &= rounding_corners_flags; window->DrawList->AddRectFilled(ImVec2(x1,y1), ImVec2(x2,y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell); } } } else { window->DrawList->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags); } } void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) { ImGuiContext& g = *GImGui; if ((flags & ImGuiColorEditFlags__InputsMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputsMask; if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask; if ((flags & ImGuiColorEditFlags__PickerMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask; IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__InputsMask))); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DataTypeMask))); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check only 1 option is selected g.ColorEditOptions = flags; } // 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. // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiID id = window->GetID(desc_id); float default_size = GetFrameHeight(); if (size.x == 0.0f) size.x = default_size; if (size.y == 0.0f) size.y = default_size; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f); if (!ItemAdd(bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); if (flags & ImGuiColorEditFlags_NoAlpha) flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf); ImVec4 col_without_alpha(col.x, col.y, col.z, 1.0f); float grid_step = ImMin(size.x, size.y) / 2.99f; float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f); ImRect bb_inner = bb; float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts. bb_inner.Expand(off); if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col.w < 1.0f) { float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f); RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight); window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft); } else { // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col : col_without_alpha; if (col_source.w < 1.0f) RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding); else window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All); } RenderNavHighlight(bb, id); if (g.Style.FrameBorderSize > 0.0f) RenderFrameBorder(bb.Min, bb.Max, rounding); else window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border // Drag and Drop Source if (g.ActiveId == id && BeginDragDropSource()) // NB: The ActiveId test is merely an optional micro-optimization { if (flags & ImGuiColorEditFlags_NoAlpha) SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col, sizeof(float) * 3, ImGuiCond_Once); else SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col, sizeof(float) * 4, ImGuiCond_Once); ColorButton(desc_id, col, flags); SameLine(); TextUnformatted("Color"); EndDragDropSource(); hovered = false; } // Tooltip if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered) ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)); return pressed; } bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags) { return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha); } void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) { bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__InputsMask); bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask); if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context")) return; ImGuiContext& g = *GImGui; ImGuiColorEditFlags opts = g.ColorEditOptions; if (allow_opt_inputs) { if (RadioButton("RGB", (opts & ImGuiColorEditFlags_RGB) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_RGB; if (RadioButton("HSV", (opts & ImGuiColorEditFlags_HSV) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HSV; if (RadioButton("HEX", (opts & ImGuiColorEditFlags_HEX) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HEX; } if (allow_opt_datatype) { if (allow_opt_inputs) Separator(); if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8; if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float; } if (allow_opt_inputs || allow_opt_datatype) Separator(); if (Button("Copy as..", ImVec2(-1,0))) OpenPopup("Copy"); if (BeginPopup("Copy")) { int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); char buf[64]; ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); if (Selectable(buf)) SetClipboardText(buf); ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca); if (Selectable(buf)) SetClipboardText(buf); if (flags & ImGuiColorEditFlags_NoAlpha) ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X", cr, cg, cb); else ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X%02X", cr, cg, cb, ca); if (Selectable(buf)) SetClipboardText(buf); EndPopup(); } g.ColorEditOptions = opts; EndPopup(); } static void ColorPickerOptionsPopup(ImGuiColorEditFlags flags, const float* ref_col) { bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask); bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar); if ((!allow_opt_picker && !allow_opt_alpha_bar) || !ImGui::BeginPopup("context")) return; ImGuiContext& g = *GImGui; if (allow_opt_picker) { ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function ImGui::PushItemWidth(picker_size.x); for (int picker_type = 0; picker_type < 2; picker_type++) { // Draw small/thumbnail version of each picker type (over an invisible button for selection) if (picker_type > 0) ImGui::Separator(); ImGui::PushID(picker_type); ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha); if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar; if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel; ImVec2 backup_pos = ImGui::GetCursorScreenPos(); if (ImGui::Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask); ImGui::SetCursorScreenPos(backup_pos); ImVec4 dummy_ref_col; memcpy(&dummy_ref_col.x, ref_col, sizeof(float) * (picker_flags & ImGuiColorEditFlags_NoAlpha ? 3 : 4)); ImGui::ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags); ImGui::PopID(); } ImGui::PopItemWidth(); } if (allow_opt_alpha_bar) { if (allow_opt_picker) ImGui::Separator(); ImGui::CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar); } ImGui::EndPopup(); } // Edit colors components (each component in 0.0f..1.0f range). // See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. // With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item. bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float square_sz = GetFrameHeight(); const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x); const float w_items_all = CalcItemWidth() - w_extra; const char* label_display_end = FindRenderedTextEnd(label); const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0; const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0; const int components = alpha ? 4 : 3; const ImGuiColorEditFlags flags_untouched = flags; BeginGroup(); PushID(label); // If we're not showing any slider there's no point in doing any HSV conversions if (flags & ImGuiColorEditFlags_NoInputs) flags = (flags & (~ImGuiColorEditFlags__InputsMask)) | ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_NoOptions; // Context menu: display and modify options (before defaults are applied) if (!(flags & ImGuiColorEditFlags_NoOptions)) ColorEditOptionsPopup(col, flags); // Read stored options if (!(flags & ImGuiColorEditFlags__InputsMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputsMask); if (!(flags & ImGuiColorEditFlags__DataTypeMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask); if (!(flags & ImGuiColorEditFlags__PickerMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask); flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask)); // Convert to the formats we need float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f }; if (flags & ImGuiColorEditFlags_HSV) ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); 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]) }; bool value_changed = false; bool value_changed_as_float = false; if ((flags & (ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_HSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB/HSV 0..255 Sliders 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((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; const char* fmt_table_int[3][4] = { { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, // Short display { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, // Long display for RGBA { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } // Long display for HSVA }; const char* fmt_table_float[3][4] = { { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA }; const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_HSV) ? 2 : 1; PushItemWidth(w_item_one); for (int n = 0; n < components; n++) { if (n > 0) SameLine(0, style.ItemInnerSpacing.x); if (n + 1 == components) PushItemWidth(w_item_last); if (flags & ImGuiColorEditFlags_Float) value_changed = value_changed_as_float = value_changed | DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); else value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]); if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); } PopItemWidth(); PopItemWidth(); } else if ((flags & ImGuiColorEditFlags_HEX) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB Hexadecimal Input char buf[64]; if (alpha) ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255)); else ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255)); PushItemWidth(w_items_all); 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]); } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); PopItemWidth(); } ImGuiWindow* picker_active_window = NULL; if (!(flags & ImGuiColorEditFlags_NoSmallPreview)) { if (!(flags & ImGuiColorEditFlags_NoInputs)) SameLine(0, style.ItemInnerSpacing.x); const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f); if (ColorButton("##ColorButton", col_v4, flags)) { if (!(flags & ImGuiColorEditFlags_NoPicker)) { // Store current color and open a picker g.ColorPickerRef = col_v4; OpenPopup("picker"); SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y)); } } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); if (BeginPopup("picker")) { picker_active_window = g.CurrentWindow; if (label != label_display_end) { TextUnformatted(label, label_display_end); Separator(); } ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); PopItemWidth(); EndPopup(); } } if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel)) { SameLine(0, style.ItemInnerSpacing.x); TextUnformatted(label, label_display_end); } // Convert back if (picker_active_window == NULL) { if (!value_changed_as_float) for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; if (flags & ImGuiColorEditFlags_HSV) ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); if (value_changed) { col[0] = f[0]; col[1] = f[1]; col[2] = f[2]; if (alpha) col[3] = f[3]; } } PopID(); EndGroup(); // Drag and Drop Target if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && BeginDragDropTarget()) // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test. { if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) { memcpy((float*)col, payload->Data, sizeof(float) * 3); value_changed = true; } if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) { memcpy((float*)col, payload->Data, sizeof(float) * components); value_changed = true; } EndDragDropTarget(); } // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4(). if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window) window->DC.LastItemId = g.ActiveId; return value_changed; } bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags) { float col4[4] = { col[0], col[1], col[2], 1.0f }; if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha)) return false; col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2]; return true; } // 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. static void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col) { switch (direction) { case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return; case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return; case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return; case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return; case ImGuiDir_None: case ImGuiDir_Count_: break; // Fix warnings } } static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w) { RenderArrow(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32_BLACK); RenderArrow(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE); RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32_BLACK); RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE); } // ColorPicker // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. // FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); ImDrawList* draw_list = window->DrawList; ImGuiStyle& style = g.Style; ImGuiIO& io = g.IO; PushID(label); BeginGroup(); if (!(flags & ImGuiColorEditFlags_NoSidePreview)) flags |= ImGuiColorEditFlags_NoSmallPreview; // Context menu: display and store options. if (!(flags & ImGuiColorEditFlags_NoOptions)) ColorPickerOptionsPopup(flags, col); // Read stored options if (!(flags & ImGuiColorEditFlags__PickerMask)) flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask; IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check that only 1 is selected if (!(flags & ImGuiColorEditFlags_NoOptions)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar); // Setup int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4; bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha); ImVec2 picker_pos = window->DC.CursorPos; float square_sz = GetFrameHeight(); float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars float sv_picker_size = ImMax(bars_width * 1, CalcItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x; float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x; float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f); float backup_initial_col[4]; memcpy(backup_initial_col, col, components * sizeof(float)); float wheel_thickness = sv_picker_size * 0.08f; float wheel_r_outer = sv_picker_size * 0.50f; float wheel_r_inner = wheel_r_outer - wheel_thickness; ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f); // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic. float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f); ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point. ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point. ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point. float H,S,V; ColorConvertRGBtoHSV(col[0], col[1], col[2], H, S, V); bool value_changed = false, value_changed_h = false, value_changed_sv = false; PushItemFlag(ImGuiItemFlags_NoNav, true); if (flags & ImGuiColorEditFlags_PickerHueWheel) { // Hue wheel + SV triangle logic InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size)); if (IsItemActive()) { ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center; ImVec2 current_off = g.IO.MousePos - wheel_center; float initial_dist2 = ImLengthSqr(initial_off); if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1)) { // Interactive with Hue wheel H = atan2f(current_off.y, current_off.x) / IM_PI*0.5f; if (H < 0.0f) H += 1.0f; value_changed = value_changed_h = true; } float cos_hue_angle = cosf(-H * 2.0f * IM_PI); float sin_hue_angle = sinf(-H * 2.0f * IM_PI); if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle))) { // Interacting with SV triangle ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle); if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated)) current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated); float uu, vv, ww; ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww); V = ImClamp(1.0f - vv, 0.0001f, 1.0f); S = ImClamp(uu / V, 0.0001f, 1.0f); value_changed = value_changed_sv = true; } } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); } else if (flags & ImGuiColorEditFlags_PickerHueBar) { // SV rectangle logic InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size)); if (IsItemActive()) { S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1)); V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); value_changed = value_changed_sv = true; } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); // Hue bar logic SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y)); InvisibleButton("hue", ImVec2(bars_width, sv_picker_size)); if (IsItemActive()) { H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); value_changed = value_changed_h = true; } } // Alpha bar logic if (alpha_bar) { SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y)); InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size)); if (IsItemActive()) { col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); value_changed = true; } } PopItemFlag(); // ImGuiItemFlags_NoNav if (!(flags & ImGuiColorEditFlags_NoSidePreview)) { SameLine(0, style.ItemInnerSpacing.x); BeginGroup(); } if (!(flags & ImGuiColorEditFlags_NoLabel)) { const char* label_display_end = FindRenderedTextEnd(label); if (label != label_display_end) { if ((flags & ImGuiColorEditFlags_NoSidePreview)) SameLine(0, style.ItemInnerSpacing.x); TextUnformatted(label, label_display_end); } } if (!(flags & ImGuiColorEditFlags_NoSidePreview)) { PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); if ((flags & ImGuiColorEditFlags_NoLabel)) Text("Current"); ColorButton("##current", col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2)); if (ref_col != NULL) { Text("Original"); ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]); if (ColorButton("##original", ref_col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2))) { memcpy(col, ref_col, components * sizeof(float)); value_changed = true; } } PopItemFlag(); EndGroup(); } // Convert back color to RGB if (value_changed_h || value_changed_sv) ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]); // R,G,B and H,S,V slider color editor if ((flags & ImGuiColorEditFlags_NoInputs) == 0) { PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x); ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf; ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker; if (flags & ImGuiColorEditFlags_RGB || (flags & ImGuiColorEditFlags__InputsMask) == 0) value_changed |= ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_RGB); if (flags & ImGuiColorEditFlags_HSV || (flags & ImGuiColorEditFlags__InputsMask) == 0) value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_HSV); if (flags & ImGuiColorEditFlags_HEX || (flags & ImGuiColorEditFlags__InputsMask) == 0) value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_HEX); PopItemWidth(); } // Try to cancel hue wrap (after ColorEdit), if any if (value_changed) { float new_H, new_S, new_V; ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V); if (new_H <= 0 && H > 0) { if (new_V <= 0 && V != new_V) ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]); else if (new_S <= 0) ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]); } } ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z); ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f); ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 1.0f)); const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) }; ImVec2 sv_cursor_pos; if (flags & ImGuiColorEditFlags_PickerHueWheel) { // Render Hue Wheel const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out). const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12); for (int n = 0; n < 6; n++) { const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps; const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps; const int vert_start_idx = draw_list->VtxBuffer.Size; draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc); draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness); const int vert_end_idx = draw_list->VtxBuffer.Size; // Paint colors over existing vertices ImVec2 gradient_p0(wheel_center.x + cosf(a0) * wheel_r_inner, wheel_center.y + sinf(a0) * wheel_r_inner); ImVec2 gradient_p1(wheel_center.x + cosf(a1) * wheel_r_inner, wheel_center.y + sinf(a1) * wheel_r_inner); ShadeVertsLinearColorGradientKeepAlpha(draw_list->VtxBuffer.Data + vert_start_idx, draw_list->VtxBuffer.Data + vert_end_idx, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n+1]); } // Render Cursor + preview on Hue Wheel float cos_hue_angle = cosf(H * 2.0f * IM_PI); float sin_hue_angle = sinf(H * 2.0f * IM_PI); ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f); float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f; int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32); draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments); draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, IM_COL32(128,128,128,255), hue_cursor_segments); draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments); // Render SV triangle (rotated according to hue) ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle); ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle); ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle); ImVec2 uv_white = GetFontTexUvWhitePixel(); draw_list->PrimReserve(6, 6); draw_list->PrimVtx(tra, uv_white, hue_color32); draw_list->PrimVtx(trb, uv_white, hue_color32); draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE); draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS); draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK); draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS); draw_list->AddTriangle(tra, trb, trc, IM_COL32(128,128,128,255), 1.5f); sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V)); } else if (flags & ImGuiColorEditFlags_PickerHueBar) { // Render SV Square draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE); draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK); RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), 0.0f); sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2); // Render Hue Bar for (int i = 0; i < 6; ++i) draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]); float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f); RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f); RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f); } // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range) float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f; draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, col32_no_alpha, 12); draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, IM_COL32(128,128,128,255), 12); draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12); // Render alpha bar if (alpha_bar) { float alpha = ImSaturate(col[3]); ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size); RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0,0,0,0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f)); draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK); float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f); RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f); RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f); } EndGroup(); PopID(); return value_changed && memcmp(backup_initial_col, col, components * sizeof(float)); } // Horizontal separating line. void ImGui::Separator() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = 0; if ((flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)) == 0) flags |= (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal; IM_ASSERT(ImIsPowerOfTwo((int)(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)))); // Check that only 1 option is selected if (flags & ImGuiSeparatorFlags_Vertical) { VerticalSeparator(); return; } // Horizontal Separator if (window->DC.ColumnsSet) PopClipRect(); 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+1.0f)); ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout. if (!ItemAdd(bb, 0)) { if (window->DC.ColumnsSet) PushColumnClipRect(); return; } window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Separator)); if (g.LogEnabled) LogRenderedText(NULL, IM_NEWLINE "--------------------------------"); if (window->DC.ColumnsSet) { PushColumnClipRect(); window->DC.ColumnsSet->CellMinY = window->DC.CursorPos.y; } } void ImGui::VerticalSeparator() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; float y1 = window->DC.CursorPos.y; float y2 = window->DC.CursorPos.y + window->DC.CurrentLineHeight; const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2)); ItemSize(ImVec2(bb.GetWidth(), 0.0f)); if (!ItemAdd(bb, 0)) return; window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator)); if (g.LogEnabled) LogText(" |"); } bool ImGui::SplitterBehavior(ImGuiID id, const ImRect& bb, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus; bool item_add = ItemAdd(bb, id); window->DC.ItemFlags = item_flags_backup; if (!item_add) return false; bool hovered, held; ImRect bb_interact = bb; bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f)); ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap); if (g.ActiveId != id) SetItemAllowOverlap(); if (held || (g.HoveredId == id && g.HoveredIdPreviousFrame == id)) SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW); ImRect bb_render = bb; if (held) { ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min; float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x; // Minimum pane size if (mouse_delta < min_size1 - *size1) mouse_delta = min_size1 - *size1; if (mouse_delta > *size2 - min_size2) mouse_delta = *size2 - min_size2; // Apply resize *size1 += mouse_delta; *size2 -= mouse_delta; bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta)); } // Render const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, g.Style.FrameRounding); return held; } void ImGui::Spacing() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ItemSize(ImVec2(0,0)); } void ImGui::Dummy(const ImVec2& size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb); ItemAdd(bb, 0); } bool ImGui::IsRectVisible(const ImVec2& size) { ImGuiWindow* window = GetCurrentWindowRead(); return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); } bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) { ImGuiWindow* window = GetCurrentWindowRead(); return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); } // 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() { ImGuiWindow* window = GetCurrentWindow(); 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.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.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; } void ImGui::EndGroup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); 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 = 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; window->DC.IndentX = group_data.BackupIndentX; window->DC.GroupOffsetX = group_data.BackupGroupOffsetX; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; 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, 0); } // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will be functional 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; window->DC.LastItemRect = group_bb; window->DC.GroupStack.pop_back(); //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 // 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) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; if (pos_x != 0.0f) { 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.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; } void ImGui::NewLine() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiLayoutType backup_layout_type = window->DC.LayoutType; window->DC.LayoutType = ImGuiLayoutType_Vertical; 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, g.FontSize)); window->DC.LayoutType = backup_layout_type; } void ImGui::NextColumn() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems || window->DC.ColumnsSet == NULL) return; ImGuiContext& g = *GImGui; PopItemWidth(); PopClipRect(); ImGuiColumnsSet* columns = window->DC.ColumnsSet; columns->CellMaxY = ImMax(columns->CellMaxY, window->DC.CursorPos.y); if (++columns->Current < columns->Count) { // Columns 1+ cancel out IndentX window->DC.ColumnsOffsetX = GetColumnOffset(columns->Current) - window->DC.IndentX + g.Style.ItemSpacing.x; window->DrawList->ChannelsSetCurrent(columns->Current); } else { window->DC.ColumnsOffsetX = 0.0f; window->DrawList->ChannelsSetCurrent(0); columns->Current = 0; columns->CellMinY = columns->CellMaxY; } window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); window->DC.CursorPos.y = columns->CellMinY; 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 = GetCurrentWindowRead(); return window->DC.ColumnsSet ? window->DC.ColumnsSet->Current : 0; } int ImGui::GetColumnsCount() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.ColumnsSet ? window->DC.ColumnsSet->Count : 1; } static float OffsetNormToPixels(const ImGuiColumnsSet* columns, float offset_norm) { return offset_norm * (columns->MaxX - columns->MinX); } static float PixelsToOffsetNorm(const ImGuiColumnsSet* columns, float offset) { return offset / (columns->MaxX - columns->MinX); } static inline float GetColumnsRectHalfWidth() { return 4.0f; } static float GetDraggedColumnOffset(ImGuiColumnsSet* columns, 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 = g.CurrentWindow; 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 == columns->ID + ImGuiID(column_index)); float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x; x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths)) x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); return x; } float ImGui::GetColumnOffset(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumnsSet* columns = window->DC.ColumnsSet; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; IM_ASSERT(column_index < columns->Columns.Size); /* if (g.ActiveId) { ImGuiContext& g = *GImGui; const ImGuiID column_id = columns->ColumnsSetId + ImGuiID(column_index); if (g.ActiveId == column_id) return GetDraggedColumnOffset(columns, column_index); } */ const float t = columns->Columns[column_index].OffsetNorm; const float x_offset = ImLerp(columns->MinX, columns->MaxX, t); return x_offset; } static float GetColumnWidthEx(ImGuiColumnsSet* columns, int column_index, bool before_resize = false) { if (column_index < 0) column_index = columns->Current; float offset_norm; if (before_resize) offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize; else offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm; return OffsetNormToPixels(columns, offset_norm); } float ImGui::GetColumnWidth(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumnsSet* columns = window->DC.ColumnsSet; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm); } void ImGui::SetColumnOffset(int column_index, float offset) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiColumnsSet* columns = window->DC.ColumnsSet; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; IM_ASSERT(column_index < columns->Columns.Size); const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1); const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow)) offset = ImMin(offset, columns->MaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->MinX); if (preserve_width) SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); } void ImGui::SetColumnWidth(int column_index, float width) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumnsSet* columns = window->DC.ColumnsSet; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width); } void ImGui::PushColumnClipRect(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumnsSet* columns = window->DC.ColumnsSet; if (column_index < 0) column_index = columns->Current; PushClipRect(columns->Columns[column_index].ClipRect.Min, columns->Columns[column_index].ClipRect.Max, false); } static ImGuiColumnsSet* FindOrAddColumnsSet(ImGuiWindow* window, ImGuiID id) { for (int n = 0; n < window->ColumnsStorage.Size; n++) if (window->ColumnsStorage[n].ID == id) return &window->ColumnsStorage[n]; window->ColumnsStorage.push_back(ImGuiColumnsSet()); ImGuiColumnsSet* columns = &window->ColumnsStorage.back(); columns->ID = id; return columns; } void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count > 1); IM_ASSERT(window->DC.ColumnsSet == NULL); // Nested columns are currently not supported // 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 + (str_id ? 0 : columns_count)); ImGuiID id = window->GetID(str_id ? str_id : "columns"); PopID(); // Acquire storage for the columns set ImGuiColumnsSet* columns = FindOrAddColumnsSet(window, id); IM_ASSERT(columns->ID == id); columns->Current = 0; columns->Count = columns_count; columns->Flags = flags; window->DC.ColumnsSet = columns; // Set state for first column const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->Size.x -window->ScrollbarSizes.x); columns->MinX = window->DC.IndentX - g.Style.ItemSpacing.x; // Lock our horizontal range //column->MaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x; columns->MaxX = content_region_width - window->Scroll.x; columns->StartPosY = window->DC.CursorPos.y; columns->StartMaxPosX = window->DC.CursorMaxPos.x; columns->CellMinY = columns->CellMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffsetX = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); // Clear data if columns count changed if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) columns->Columns.resize(0); // Initialize defaults columns->IsFirstFrame = (columns->Columns.Size == 0); if (columns->Columns.Size == 0) { columns->Columns.reserve(columns_count + 1); for (int n = 0; n < columns_count + 1; n++) { ImGuiColumnData column; column.OffsetNorm = n / (float)columns_count; columns->Columns.push_back(column); } } for (int n = 0; n < columns_count + 1; n++) { // Clamp position ImGuiColumnData* column = &columns->Columns[n]; float t = column->OffsetNorm; if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow)) t = ImMin(t, PixelsToOffsetNorm(columns, (columns->MaxX - columns->MinX) - g.Style.ColumnsMinSpacing * (columns->Count - n))); column->OffsetNorm = t; if (n == columns_count) continue; // Compute clipping rectangle float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f); float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f); column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); column->ClipRect.ClipWith(window->ClipRect); } window->DrawList->ChannelsSplit(columns->Count); PushColumnClipRect(); PushItemWidth(GetColumnWidth() * 0.65f); } void ImGui::EndColumns() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); ImGuiColumnsSet* columns = window->DC.ColumnsSet; IM_ASSERT(columns != NULL); PopItemWidth(); PopClipRect(); window->DrawList->ChannelsMerge(); columns->CellMaxY = ImMax(columns->CellMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = columns->CellMaxY; if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize)) window->DC.CursorMaxPos.x = ImMax(columns->StartMaxPosX, columns->MaxX); // Restore cursor max pos, as columns don't grow parent // Draw columns borders and handle resize bool is_being_resized = false; if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems) { const float y1 = columns->StartPosY; const float y2 = window->DC.CursorPos.y; int dragging_column = -1; for (int n = 1; n < columns->Count; n++) { float x = window->Pos.x + GetColumnOffset(n); const ImGuiID column_id = columns->ID + ImGuiID(n); const float column_hw = GetColumnsRectHalfWidth(); // Half-width for interaction const ImRect column_rect(ImVec2(x - column_hw, y1), ImVec2(x + column_hw, y2)); KeepAliveID(column_id); if (IsClippedEx(column_rect, column_id, false)) continue; bool hovered = false, held = false; if (!(columns->Flags & ImGuiColumnsFlags_NoResize)) { ButtonBehavior(column_rect, column_id, &hovered, &held); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeEW; if (held && !(columns->Columns[n].Flags & ImGuiColumnsFlags_NoResize)) dragging_column = n; } // Draw column (we clip the Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.) const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); const float xi = (float)(int)x; window->DrawList->AddLine(ImVec2(xi, ImMax(y1 + 1.0f, window->ClipRect.Min.y)), ImVec2(xi, ImMin(y2, window->ClipRect.Max.y)), col); } // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. if (dragging_column != -1) { if (!columns->IsBeingResized) for (int n = 0; n < columns->Count + 1; n++) columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; columns->IsBeingResized = is_being_resized = true; float x = GetDraggedColumnOffset(columns, dragging_column); SetColumnOffset(dragging_column, x); } } columns->IsBeingResized = is_being_resized; window->DC.ColumnsSet = NULL; window->DC.ColumnsOffsetX = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); } // [2017/12: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing] void ImGui::Columns(int columns_count, const char* id, bool border) { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count != columns_count) EndColumns(); ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder); //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior if (columns_count != 1) BeginColumns(id, columns_count, flags); } void ImGui::Indent(float indent_w) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); 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::Unindent(float indent_w) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); 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(); Indent(); window->DC.TreeDepth++; PushID(str_id ? str_id : "#TreePush"); } void ImGui::TreePush(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); 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() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; Unindent(); window->DC.TreeDepth--; if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) if (g.NavIdIsAlive && (window->DC.TreeDepthMayCloseOnPop & (1 << window->DC.TreeDepth))) { SetNavID(window->IDStack.back(), g.NavLayer); NavMoveRequestCancel(); } window->DC.TreeDepthMayCloseOnPop &= (1 << window->DC.TreeDepth) - 1; PopID(); } void ImGui::Value(const char* prefix, bool b) { Text("%s: %s", prefix, (b ? "true" : "false")); } void ImGui::Value(const char* prefix, int v) { Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, unsigned int v) { Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, float v, const char* float_format) { if (float_format) { char fmt[64]; ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); Text(fmt, prefix, v); } else { Text("%s: %.3f", prefix, v); } } //----------------------------------------------------------------------------- // DRAG AND DROP //----------------------------------------------------------------------------- void ImGui::ClearDragDrop() { ImGuiContext& g = *GImGui; g.DragDropActive = false; g.DragDropPayload.Clear(); g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0; g.DragDropAcceptIdCurrRectSurface = FLT_MAX; g.DragDropAcceptFrameCount = -1; } // Call when current ID is active. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource() bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags, int mouse_button) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; bool source_drag_active = false; ImGuiID source_id = 0; ImGuiID source_parent_id = 0; if (!(flags & ImGuiDragDropFlags_SourceExtern)) { source_id = window->DC.LastItemId; if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case return false; if (g.IO.MouseDown[mouse_button] == false) return false; if (source_id == 0) { // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to: // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID)) { IM_ASSERT(0); return false; } // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image() // We build a throwaway ID based on current ID stack + relative AABB of items in window. // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive. bool is_hovered = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) != 0; if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window)) return false; source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect); if (is_hovered) SetHoveredID(source_id); if (is_hovered && g.IO.MouseClicked[mouse_button]) { SetActiveID(source_id, window); FocusWindow(window); } if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker. g.ActiveIdAllowOverlap = is_hovered; } if (g.ActiveId != source_id) return false; source_parent_id = window->IDStack.back(); source_drag_active = IsMouseDragging(mouse_button); } else { window = NULL; source_id = ImHash("#SourceExtern", 0); source_drag_active = true; } if (source_drag_active) { if (!g.DragDropActive) { IM_ASSERT(source_id != 0); ClearDragDrop(); ImGuiPayload& payload = g.DragDropPayload; payload.SourceId = source_id; payload.SourceParentId = source_parent_id; g.DragDropActive = true; g.DragDropSourceFlags = flags; g.DragDropMouseButton = mouse_button; } if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) { // FIXME-DRAG //SetNextWindowPos(g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding); //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This is better but e.g ColorButton with checkboard has issue with transparent colors :( SetNextWindowPos(g.IO.MousePos); PushStyleColor(ImGuiCol_PopupBg, GetStyleColorVec4(ImGuiCol_PopupBg) * ImVec4(1.0f, 1.0f, 1.0f, 0.6f)); BeginTooltip(); } if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern)) window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect; return true; } return false; } void ImGui::EndDragDropSource() { ImGuiContext& g = *GImGui; IM_ASSERT(g.DragDropActive); if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) { EndTooltip(); PopStyleColor(); //PopStyleVar(); } // Discard the drag if have not called SetDragDropPayload() if (g.DragDropPayload.DataFrameCount == -1) ClearDragDrop(); } // Use 'cond' to choose to submit payload on drag start or every frame bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond) { ImGuiContext& g = *GImGui; ImGuiPayload& payload = g.DragDropPayload; if (cond == 0) cond = ImGuiCond_Always; IM_ASSERT(type != NULL); IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 12 characters long"); IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0)); IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once); IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource() if (cond == ImGuiCond_Always || payload.DataFrameCount == -1) { // Copy payload ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType)); g.DragDropPayloadBufHeap.resize(0); if (data_size > sizeof(g.DragDropPayloadBufLocal)) { // Store in heap g.DragDropPayloadBufHeap.resize((int)data_size); payload.Data = g.DragDropPayloadBufHeap.Data; memcpy((void*)payload.Data, data, data_size); } else if (data_size > 0) { // Store locally memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); payload.Data = g.DragDropPayloadBufLocal; memcpy((void*)payload.Data, data, data_size); } else { payload.Data = NULL; } payload.DataSize = (int)data_size; } payload.DataFrameCount = g.FrameCount; return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1); } bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) { ImGuiContext& g = *GImGui; if (!g.DragDropActive) return false; ImGuiWindow* window = g.CurrentWindow; if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) return false; IM_ASSERT(id != 0); if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId)) return false; g.DragDropTargetRect = bb; g.DragDropTargetId = id; return true; } // We don't use BeginDragDropTargetCustom() and duplicate its code because: // 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them. // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can. // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case) bool ImGui::BeginDragDropTarget() { ImGuiContext& g = *GImGui; if (!g.DragDropActive) return false; ImGuiWindow* window = g.CurrentWindow; if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) return false; if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) return false; const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect; ImGuiID id = window->DC.LastItemId; if (id == 0) id = window->GetIDFromRectangle(display_rect); if (g.DragDropPayload.SourceId == id) return false; g.DragDropTargetRect = display_rect; g.DragDropTargetId = id; return true; } bool ImGui::IsDragDropPayloadBeingAccepted() { ImGuiContext& g = *GImGui; return g.DragDropActive && g.DragDropAcceptIdPrev != 0; } const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiPayload& payload = g.DragDropPayload; IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ? IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ? if (type != NULL && !payload.IsDataType(type)) return NULL; // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints. // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function! const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId); ImRect r = g.DragDropTargetRect; float r_surface = r.GetWidth() * r.GetHeight(); if (r_surface < g.DragDropAcceptIdCurrRectSurface) { g.DragDropAcceptIdCurr = g.DragDropTargetId; g.DragDropAcceptIdCurrRectSurface = r_surface; } // Render default drop visuals payload.Preview = was_accepted_previously; flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame) if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview) { // FIXME-DRAG: Settle on a proper default visuals for drop target. r.Expand(3.5f); bool push_clip_rect = !window->ClipRect.Contains(r); if (push_clip_rect) window->DrawList->PushClipRectFullScreen(); window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f); if (push_clip_rect) window->DrawList->PopClipRect(); } g.DragDropAcceptFrameCount = g.FrameCount; payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased() if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery)) return NULL; return &payload; } // We don't really use/need this now, but added it for the sake of consistency and because we might need it later. void ImGui::EndDragDropTarget() { ImGuiContext& g = *GImGui; (void)g; IM_ASSERT(g.DragDropActive); } //----------------------------------------------------------------------------- // PLATFORM DEPENDENT HELPERS //----------------------------------------------------------------------------- #if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)) #undef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #ifndef __MINGW32__ #include #else #include #endif #endif // Win32 API clipboard implementation #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) #ifdef _MSC_VER #pragma comment(lib, "user32") #endif static const char* GetClipboardTextFn_DefaultImpl(void*) { static ImVector buf_local; buf_local.clear(); if (!OpenClipboard(NULL)) return NULL; HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT); if (wbuf_handle == NULL) { CloseClipboard(); return NULL; } if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle)) { 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; } static void SetClipboardTextFn_DefaultImpl(void*, 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) { CloseClipboard(); 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(void*) { ImGuiContext& g = *GImGui; return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin(); } // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { ImGuiContext& g = *GImGui; g.PrivateClipboard.clear(); const char* text_end = text + strlen(text); g.PrivateClipboard.resize((int)(text_end - text) + 1); memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text)); g.PrivateClipboard[(int)(text_end - text)] = 0; } #endif // Win32 API IME support (for Asian languages, etc.) #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) #include #ifdef _MSC_VER #pragma comment(lib, "imm32") #endif 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 //----------------------------------------------------------------------------- // HELP //----------------------------------------------------------------------------- void ImGui::ShowMetricsWindow(bool* p_open) { if (ImGui::Begin("ImGui Metrics", p_open)) { ImGui::Text("Dear 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", (int)GImAllocatorActiveAllocationsCount); static bool show_clip_rects = true; ImGui::Checkbox("Show clipping rectangles when hovering draw commands", &show_clip_rects); ImGui::Separator(); struct Funcs { static void NodeDrawList(ImGuiWindow* window, 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; } ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list if (window && ImGui::IsItemHovered()) overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); if (!node_open) return; 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 == NULL && pcmd->ElemCount == 0) continue; 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 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.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; // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. 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]; char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(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 += ImFormatString(buf_p, (int)(buf_end - 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()) { ImDrawListFlags backup_flags = overlay_draw_list->Flags; overlay_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles. overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f); overlay_draw_list->Flags = backup_flags; } } ImGui::TreePop(); } ImGui::TreePop(); } static void NodeWindows(ImVector& 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; ImGuiWindowFlags flags = window->Flags; NodeDrawList(window, window->DrawList, "DrawList"); ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y); ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s..)", flags, (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : ""); ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetScrollMaxX(window), window->Scroll.y, GetScrollMaxY(window)); ImGui::BulletText("Active: %d, WriteAccessed: %d", window->Active, window->WriteAccessed); ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask); ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); if (window->NavRectRel[0].IsFinite()) ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y); else ImGui::BulletText("NavRectRel[0]: "); 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(); } }; // Access private state, we are going to display the draw lists from last frame ImGuiContext& g = *GImGui; Funcs::NodeWindows(g.Windows, "Windows"); if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size)) { for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++) Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList"); ImGui::TreePop(); } 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("Internal state")) { const char* input_source_names[] = { "None", "Mouse", "Nav", "NavGamepad", "NavKeyboard" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_Count_); 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 (%.2f sec)", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer); // 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 (%.2f sec), ActiveIdSource: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, input_source_names[g.ActiveIdSource]); ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId); ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover); ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); ImGui::TreePop(); } } ImGui::End(); } //----------------------------------------------------------------------------- // 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 //----------------------------------------------------------------------------- ================================================ FILE: ui/imgui/imgui.h ================================================ // dear imgui, v1.60 WIP // (headers) // See imgui.cpp file for documentation. // Call and read ImGui::ShowDemoWindow() 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 // User-editable configuration files (edit stock imconfig.h or define IMGUI_USER_CONFIG to your own filename) #ifdef IMGUI_USER_CONFIG #include IMGUI_USER_CONFIG #endif #if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H) #include "imconfig.h" #endif #include // FLT_MAX #include // va_list #include // ptrdiff_t, NULL #include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp #define IMGUI_VERSION "1.60 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 #define IM_ASSERT(_EXPR) assert(_EXPR) #endif // Helpers // Some compilers support applying printf-style warnings to user functions. #if defined(__clang__) || defined(__GNUC__) #define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) #define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) #else #define IM_FMTARGS(FMT) #define IM_FMTLIST(FMT) #endif #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) #define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in modern C++. #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 ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) 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/OTF 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 ImGuiSizeCallbackData; // Structure used to constraint window size in custom ways when using custom ImGuiSizeCallback (rare/advanced use) struct ImGuiListClipper; // Helper to manually clip large list of items struct ImGuiPayload; // User data payload for drag and drop operations 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; // enum: a color identifier for styling // enum ImGuiCol_ typedef int ImGuiCond; // enum: a condition for Set*() // enum ImGuiCond_ typedef int ImGuiKey; // enum: a key identifier (ImGui-side enum) // enum ImGuiKey_ typedef int ImGuiNavInput; // enum: an input identifier for navigation // enum ImGuiNavInput_ typedef int ImGuiMouseCursor; // enum: a mouse cursor identifier // enum ImGuiMouseCursor_ typedef int ImGuiStyleVar; // enum: a variable identifier for styling // enum ImGuiStyleVar_ typedef int ImDrawCornerFlags; // flags: for ImDrawList::AddRect*() etc. // enum ImDrawCornerFlags_ typedef int ImDrawListFlags; // flags: for ImDrawList // enum ImDrawListFlags_ typedef int ImFontAtlasFlags; // flags: for ImFontAtlas // enum ImFontAtlasFlags_ typedef int ImGuiColorEditFlags; // flags: for ColorEdit*(), ColorPicker*() // enum ImGuiColorEditFlags_ typedef int ImGuiColumnsFlags; // flags: for *Columns*() // enum ImGuiColumnsFlags_ typedef int ImGuiDragDropFlags; // flags: for *DragDrop*() // enum ImGuiDragDropFlags_ typedef int ImGuiComboFlags; // flags: for BeginCombo() // enum ImGuiComboFlags_ typedef int ImGuiFocusedFlags; // flags: for IsWindowFocused() // enum ImGuiFocusedFlags_ typedef int ImGuiHoveredFlags; // flags: for IsItemHovered() etc. // enum ImGuiHoveredFlags_ typedef int ImGuiInputTextFlags; // flags: for InputText*() // enum ImGuiInputTextFlags_ typedef int ImGuiNavFlags; // flags: for io.NavFlags // enum ImGuiNavFlags_ typedef int ImGuiSelectableFlags; // flags: for Selectable() // enum ImGuiSelectableFlags_ typedef int ImGuiTreeNodeFlags; // flags: for TreeNode*(),CollapsingHeader()// enum ImGuiTreeNodeFlags_ typedef int ImGuiWindowFlags; // flags: for Begin*() // enum ImGuiWindowFlags_ typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data); typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); #if defined(_MSC_VER) && !defined(__clang__) typedef unsigned __int64 ImU64; // 64-bit unsigned integer #else typedef unsigned long long ImU64; // 64-bit unsigned integer #endif // 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; } float operator[] (size_t idx) const { IM_ASSERT(idx == 0 || idx == 1); return *(&x + idx); } // We very rarely use this [] operator, thus an assert is fine. #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 { // Context creation and access, if you want to use multiple context, share context between modules (e.g. DLL). // 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. // All those functions are not reliant on the current context. IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL); IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = Destroy current context IMGUI_API ImGuiContext* GetCurrentContext(); IMGUI_API void SetCurrentContext(ImGuiContext* ctx); // Main IMGUI_API ImGuiIO& GetIO(); IMGUI_API ImGuiStyle& GetStyle(); IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until Render()/EndFrame(). IMGUI_API void Render(); // ends the ImGui frame, finalize the draw data. (Obsolete: optionally call io.RenderDrawListsFn if set. Nowadays, prefer calling your render function yourself.) IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. (Obsolete: this used to be passed to your io.RenderDrawListsFn() function.) IMGUI_API void EndFrame(); // ends the ImGui frame. automatically called by Render(), so most likely don't need to ever call that yourself directly. If you don't need to render you may call EndFrame() but you'll have wasted CPU already. If you don't need to render, better to not create any imgui windows instead! // Demo, Debug, Informations IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create demo/test window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics window. display ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc. IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) IMGUI_API bool ShowStyleSelector(const char* label); IMGUI_API void ShowFontSelector(const char* label); IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls). IMGUI_API const char* GetVersion(); // Styles IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // New, recommended style IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // Classic imgui style (default) IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // Best used with borders and a custom, thicker font // 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) but you always need to call End() regardless. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false). IMGUI_API void End(); // always call even if Begin() return false (which indicates a collapsed window)! 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 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 flags = 0); // " IMGUI_API void EndChild(); // always call even if BeginChild() return false (which indicates a collapsed or clipping child window) 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 bool IsWindowAppearing(); 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, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0,0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond 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, ImGuiSizeCallback 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). not including window decorations (title bar, menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin() IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond 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 SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg. IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond 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, ImGuiCond 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, ImGuiCond 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, ImGuiCond cond = 0); // set named window position. IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond 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, ImGuiCond 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. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. 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 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, ImU32 col); 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 const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwhise use GetColorU32() to get style color + style alpha. 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 IMGUI_API ImU32 GetColorU32(ImU32 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 allow_keyboard_focus); // 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 (using io.KeyRepeatDelay/io.KeyRepeatRate setting). 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(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. 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 AlignTextToFramePadding(); // vertically align/lower upcoming text to FramePadding.y so that it will aligns to upcoming widgets (call if you have text on a line before regular widgets) IMGUI_API float GetTextLineHeight(); // ~ FontSize IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text) IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2 IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets) // Columns // You can also use SameLine(pos_x) for simplified columns. 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); IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished IMGUI_API int GetColumnIndex(); // get current column index IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column 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 typically 0.0f 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 int GetColumnsCount(); // ID scopes // If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop index) 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). e.g. if you want to query into ImGuiStorage yourself IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); IMGUI_API ImGuiID GetID(const void* ptr_id); // Widgets: Text IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // simple formatted text IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(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) IM_FMTLIST(1); IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(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) IM_FMTLIST(2); IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); 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 // Widgets: Main 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) to easily embed within text IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) 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 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: Combo Box // The new BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it. // The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0); IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true! IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1); IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\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 popup_max_height_in_items = -1); // 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, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x // Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). 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 for in-slider labels or unit display. 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: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.) // Note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can the pass the address of a first float element out of a contiguous structure, e.g. &myvector.x IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0)); // display a colored square/button, hover for details, return true when pressed. IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. // 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_FMTARGS(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_FMTARGS(2); // " IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); IMGUI_API void TreePush(const char* str_id); // ~ 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, ImGuiCond 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)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. 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)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. IMGUI_API bool ListBox(const char* label, int* current_item, const char* const 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); // Tooltips IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set text tooltip under mouse-cursor, typically use with ImGui::IsItemHovered(). overidde any previous call to SetTooltip(). IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of contents). IMGUI_API void EndTooltip(); // Menus IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true! IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true! 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(); // only call EndBegin() if BeginMenu() returns true! 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); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). 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, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true! IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, int mouse_button = 1, bool also_over_items = true); // 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 (where there are no imgui windows). IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside) IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, int mouse_button = 1); // helper to open popup when clicked on last item. return true when just opened. IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. // Logging/Capture: all text output from interface is captured 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_FMTARGS(1); // pass text data straight to log (without being displayed) // Drag and Drop // [BETA API] Missing Demo code. API may evolve. IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0, int mouse_button = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource() IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t size, ImGuiCond cond = 0);// type is a user defined string of maximum 12 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive an item. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! // 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(); // Focus, Activation // (Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHere()" when applicable, to make your code more forward compatible when navigation branch is merged) IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window. Please use instead of "if (IsWindowAppearing()) SetScrollHere()" to signify "default item". 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 -1 to access previous widget. // Utilities IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options. IMGUI_API bool IsItemActive(); // is 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 IsItemFocused(); // is the last item focused for keyboard/gamepad navigation? IMGUI_API bool IsItemClicked(int mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on) IMGUI_API bool IsItemVisible(); // is the last item visible? (aka not out of sight due to clipping/scrolling.) IMGUI_API bool IsAnyItemHovered(); IMGUI_API bool IsAnyItemActive(); IMGUI_API bool IsAnyItemFocused(); IMGUI_API ImVec2 GetItemRectMin(); // get bounding rectangle of last item, in screen space IMGUI_API ImVec2 GetItemRectMax(); // " IMGUI_API ImVec2 GetItemRectSize(); // get size of last item, in screen space 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 IsWindowFocused(ImGuiFocusedFlags flags = 0); // is current window focused? or its root/child, depending on flags. see flags for options. IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags = 0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. 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 float GetTime(); IMGUI_API int GetFrameCount(); IMGUI_API ImDrawList* GetOverlayDrawList(); // this draw list will be the last rendered one, useful to quickly draw overlays shapes/text IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); IMGUI_API const char* GetStyleColorName(ImGuiCol idx); 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 flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window) 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 imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]! IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down).. IMGUI_API int GetKeyPressedAmount(int key_index, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate IMGUI_API bool IsMouseDown(int button); // is mouse button held IMGUI_API bool IsAnyMouseDown(); // is any 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 IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold 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 IsMousePosValid(const ImVec2* mouse_pos = NULL); // 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 is 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). // Clipboard Utilities (also see the LogToClipboard() function to capture or output text data to the clipboard) IMGUI_API const char* GetClipboardText(); IMGUI_API void SetClipboardText(const char* text); // Memory Utilities // All those functions are not reliant on the current context. // If you reload the contents of imgui.cpp at runtime, you may need to call SetCurrentContext() + SetAllocatorFunctions() again. IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data = NULL); IMGUI_API void* MemAlloc(size_t size); IMGUI_API void MemFree(void* ptr); } // namespace ImGui // Flags for ImGui::Begin() enum ImGuiWindowFlags_ { 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. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. 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 (OBSOLETE! Use e.g. style.FrameBorderSize=1.0f to enable borders). ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs, hovering test with pass through. 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) ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // (WIP) Enable resize from any corners and borders. Your back-end needs to honor the different values of io.MouseCursor set by imgui. ImGuiWindowFlags_NoNavInputs = 1 << 18, // No gamepad/keyboard navigation within the window ImGuiWindowFlags_NoNavFocus = 1 << 19, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB) ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, // [Internal] ImGuiWindowFlags_NavFlattened = 1 << 23, // (WIP) Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!) ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip() ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup() ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal() ImGuiWindowFlags_ChildMenu = 1 << 28 // Don't use! For internal use by BeginMenu() }; // Flags for ImGui::InputText() enum ImGuiInputTextFlags_ { 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, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line 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 '*' ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). // [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_AllowItemOverlap = 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_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding(). //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 11, // FIXME: TODO: Extend hit box horizontally even if not framed //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 12, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible ImGuiTreeNodeFlags_NavCloseFromChild = 1 << 13, // (WIP) Nav: left direction may close this TreeNode() when focusing on any child (items submitted between TreeNode and TreePop) ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiTreeNodeFlags_AllowOverlapMode = ImGuiTreeNodeFlags_AllowItemOverlap #endif }; // Flags for ImGui::Selectable() enum ImGuiSelectableFlags_ { 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 }; // Flags for ImGui::BeginCombo() enum ImGuiComboFlags_ { ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default) ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest }; // Flags for ImGui::IsWindowFocused() enum ImGuiFocusedFlags_ { ImGuiFocusedFlags_ChildWindows = 1 << 0, // IsWindowFocused(): Return true if any children of the window is focused ImGuiFocusedFlags_RootWindow = 1 << 1, // IsWindowFocused(): Test from root window (top most parent of the current hierarchy) ImGuiFocusedFlags_AnyWindow = 1 << 2, // IsWindowFocused(): Return true if any window is focused ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows }; // Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered() enum ImGuiHoveredFlags_ { ImGuiHoveredFlags_Default = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 3, // Return true even if a popup window is normally blocking access to this item/window //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 4, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 5, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 6, // Return true even if the position is overlapped by another window ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows }; // Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() enum ImGuiDragDropFlags_ { // BeginDragDropSource() flags ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior. ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return true, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item. ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. // AcceptDragDropPayload() flags ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect // For peeking ahead and inspecting the payload before delivery. }; // Standard Drag and Drop payload types. You can define you own payload types using 12-characters long strings. Types starting with '_' are defined by Dear ImGui. #define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3] // Standard type for colors, without alpha. User code may use this type. #define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4] // Standard type for colors. User code may use this type. // 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_PageUp, ImGuiKey_PageDown, ImGuiKey_Home, ImGuiKey_End, ImGuiKey_Insert, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, 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 }; // [BETA] Gamepad/Keyboard directional navigation // Keyboard: Set io.NavFlags |= ImGuiNavFlags_EnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeyDown[] + io.KeyMap[] arrays. // Gamepad: Set io.NavFlags |= ImGuiNavFlags_EnableGamepad to enable. Fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame(). // Read instructions in imgui.cpp for more details. enum ImGuiNavInput_ { // Gamepad Mapping ImGuiNavInput_Activate, // activate / open / toggle / tweak value // e.g. Circle (PS4), A (Xbox), B (Switch), Space (Keyboard) ImGuiNavInput_Cancel, // cancel / close / exit // e.g. Cross (PS4), B (Xbox), A (Switch), Escape (Keyboard) ImGuiNavInput_Input, // text input / on-screen keyboard // e.g. Triang.(PS4), Y (Xbox), X (Switch), Return (Keyboard) ImGuiNavInput_Menu, // tap: toggle menu / hold: focus, move, resize // e.g. Square (PS4), X (Xbox), Y (Switch), Alt (Keyboard) ImGuiNavInput_DpadLeft, // move / tweak / resize window (w/ PadMenu) // e.g. D-pad Left/Right/Up/Down (Gamepads), Arrow keys (Keyboard) ImGuiNavInput_DpadRight, // ImGuiNavInput_DpadUp, // ImGuiNavInput_DpadDown, // ImGuiNavInput_LStickLeft, // scroll / move window (w/ PadMenu) // e.g. Left Analog Stick Left/Right/Up/Down ImGuiNavInput_LStickRight, // ImGuiNavInput_LStickUp, // ImGuiNavInput_LStickDown, // ImGuiNavInput_FocusPrev, // next window (w/ PadMenu) // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch) ImGuiNavInput_FocusNext, // prev window (w/ PadMenu) // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch) ImGuiNavInput_TweakSlow, // slower tweaks // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch) ImGuiNavInput_TweakFast, // faster tweaks // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch) // [Internal] Don't use directly! This is used internally to differentiate keyboard from gamepad inputs for behaviors that require to differentiate them. // Keyboard behavior that have no corresponding gamepad mapping (e.g. CTRL+TAB) may be directly reading from io.KeyDown[] instead of io.NavInputs[]. ImGuiNavInput_KeyMenu_, // toggle menu // = io.KeyAlt ImGuiNavInput_KeyLeft_, // move left // = Arrow keys ImGuiNavInput_KeyRight_, // move right ImGuiNavInput_KeyUp_, // move up ImGuiNavInput_KeyDown_, // move down ImGuiNavInput_COUNT, ImGuiNavInput_InternalStart_ = ImGuiNavInput_KeyMenu_ }; // [BETA] Gamepad/Keyboard directional navigation options enum ImGuiNavFlags_ { ImGuiNavFlags_EnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.KeyDown[]. ImGuiNavFlags_EnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui back-end to fill io.NavInputs[]. ImGuiNavFlags_MoveMouse = 1 << 2, // Request navigation to allow moving the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantMoveMouse=true. If enabled you MUST honor io.WantMoveMouse requests in your binding, otherwise ImGui will react as if the mouse is jumping around back and forth. ImGuiNavFlags_NoCaptureKeyboard = 1 << 3 // Do not set the io.WantCaptureKeyboard flag with io.NavActive is set. }; // Enumeration for PushStyleColor() / PopStyleColor() enum ImGuiCol_ { ImGuiCol_Text, ImGuiCol_TextDisabled, ImGuiCol_WindowBg, // Background of normal windows ImGuiCol_ChildBg, // 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_TitleBgActive, ImGuiCol_TitleBgCollapsed, ImGuiCol_MenuBarBg, ImGuiCol_ScrollbarBg, ImGuiCol_ScrollbarGrab, ImGuiCol_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabActive, ImGuiCol_CheckMark, ImGuiCol_SliderGrab, ImGuiCol_SliderGrabActive, ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive, ImGuiCol_Header, ImGuiCol_HeaderHovered, ImGuiCol_HeaderActive, ImGuiCol_Separator, ImGuiCol_SeparatorHovered, ImGuiCol_SeparatorActive, 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_DragDropTarget, ImGuiCol_NavHighlight, // gamepad/keyboard: current highlighted item ImGuiCol_NavWindowingHighlight, // gamepad/keyboard: when holding NavMenu to focus/move/resize windows ImGuiCol_COUNT // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS //, ImGuiCol_ComboBg = ImGuiCol_PopupBg // ComboBg has been merged with PopupBg, so a redirect isn't accurate. , ImGuiCol_ChildWindowBg = ImGuiCol_ChildBg, ImGuiCol_Column = ImGuiCol_Separator, ImGuiCol_ColumnHovered = ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive = ImGuiCol_SeparatorActive #endif }; // Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. // NB: the enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. During initialization, feel free to just poke into ImGuiStyle directly. // NB: if changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. enum ImGuiStyleVar_ { // Enum name ......................// Member in ImGuiStyle structure (see ImGuiStyle for descriptions) ImGuiStyleVar_Alpha, // float Alpha ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding ImGuiStyleVar_WindowRounding, // float WindowRounding ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign ImGuiStyleVar_ChildRounding, // float ChildRounding ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize ImGuiStyleVar_PopupRounding, // float PopupRounding ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize ImGuiStyleVar_FramePadding, // ImVec2 FramePadding ImGuiStyleVar_FrameRounding, // float FrameRounding ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing ImGuiStyleVar_IndentSpacing, // float IndentSpacing ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding ImGuiStyleVar_GrabMinSize, // float GrabMinSize ImGuiStyleVar_GrabRounding, // float GrabRounding ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign ImGuiStyleVar_Count_ // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiStyleVar_ChildWindowRounding = ImGuiStyleVar_ChildRounding #endif }; // Enumeration for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() enum ImGuiColorEditFlags_ { ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (read 3 components from the input pointer). ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square. ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs) ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview colored square). ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead. // User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user choose and/or call SetColorEditOptions() during startup. ImGuiColorEditFlags_AlphaBar = 1 << 9, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. ImGuiColorEditFlags_AlphaPreview = 1 << 10, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 11, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. ImGuiColorEditFlags_HDR = 1 << 12, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). ImGuiColorEditFlags_RGB = 1 << 13, // [Inputs] // ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: choose any combination using RGB/HSV/HEX. ImGuiColorEditFlags_HSV = 1 << 14, // [Inputs] // " ImGuiColorEditFlags_HEX = 1 << 15, // [Inputs] // " ImGuiColorEditFlags_Uint8 = 1 << 16, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. ImGuiColorEditFlags_Float = 1 << 17, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. ImGuiColorEditFlags_PickerHueBar = 1 << 18, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value. ImGuiColorEditFlags_PickerHueWheel = 1 << 19, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value. // Internals/Masks ImGuiColorEditFlags__InputsMask = ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_HSV|ImGuiColorEditFlags_HEX, ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float, ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar, ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions() }; // Enumeration for GetMouseCursor() enum ImGuiMouseCursor_ { ImGuiMouseCursor_None = -1, ImGuiMouseCursor_Arrow = 0, ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. ImGuiMouseCursor_ResizeAll, // Unused ImGuiMouseCursor_ResizeNS, // When hovering over an horizontal border ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window ImGuiMouseCursor_Count_ }; // Condition for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions // All those functions treat 0 as a shortcut to ImGuiCond_Always. From the point of view of the user use this as an enum (don't combine multiple values into flags). enum ImGuiCond_ { ImGuiCond_Always = 1 << 0, // Set the variable ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the window has no saved data (if doesn't exist in the .ini file) ImGuiCond_Appearing = 1 << 3 // Set the variable if the window is appearing after being hidden/inactive (or the first time) // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiSetCond_Always = ImGuiCond_Always, ImGuiSetCond_Once = ImGuiCond_Once, ImGuiSetCond_FirstUseEver = ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing = ImGuiCond_Appearing #endif }; // You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame(). // During the frame, prefer using ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors. struct ImGuiStyle { float Alpha; // Global alpha applies to everything in ImGui. ImVec2 WindowPadding; // Padding within a window. float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints(). ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows. float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). float PopupRounding; // Radius of popup window corners rounding. float PopupBorderSize; // Thickness of border around popup windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). 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). float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). 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. float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. bool AntiAliasedFill; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. ImVec4 Colors[ImGuiCol_COUNT]; IMGUI_API ImGuiStyle(); IMGUI_API void ScaleAllSizes(float scale_factor); }; // 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; // // 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). ImGuiNavFlags NavFlags; // = 0 // See ImGuiNavFlags_. Gamepad/keyboard navigation options. 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]; // // Map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. 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.050f // 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; // // 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. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. 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; // (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; // (0.0f,0.0f) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize // Advanced/subtle behaviors bool OptMacOSXBehaviors; // = 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 bool OptCursorBlink; // = true // Enable blinking cursor, for users who consider it annoying. //------------------------------------------------------------------ // Settings (User Functions) //------------------------------------------------------------------ // 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* user_data); void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; // 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. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // [OBSOLETE] Rendering function, will be automatically called in Render(). Please call your rendering function yourself now! You can obtain the ImDrawData* by calling ImGui::GetDrawData() after Render(). // See example applications if you are unsure of how to implement this. void (*RenderDrawListsFn)(ImDrawData* data); #endif //------------------------------------------------------------------ // Input - Fill before calling NewFrame() //------------------------------------------------------------------ ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (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. float MouseWheelH; // Mouse wheel (Horizontal). Most users don't have a mouse with an horizontal wheel, may not be filled by all back ends. 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 (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. float NavInputs[ImGuiNavInput_COUNT]; // Gamepad inputs (keyboard keys will be auto-mapped and be written here by ImGui::NewFrame) // Functions IMGUI_API void AddInputCharacter(ImWchar c); // Add new character into InputCharacters[] IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Add new characters into InputCharacters[] from an UTF-8 string inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Clear the text input buffer manually //------------------------------------------------------------------ // Output - Retrieve after calling NewFrame() //------------------------------------------------------------------ bool WantCaptureMouse; // When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. This is set by ImGui when it wants to use your mouse (e.g. unclicked mouse is hovering a window, or a widget is active). bool WantCaptureKeyboard; // When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. This is set by ImGui when it wants to use your keyboard inputs. bool WantTextInput; // Mobile/console: when io.WantTextInput is true, you may display an on-screen keyboard. This is set by ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). bool WantMoveMouse; // MousePos has been altered, back-end should reposition mouse on next frame. Set only when ImGuiNavFlags_MoveMouse flag is enabled in io.NavFlags. bool NavActive; // Directional navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag. bool NavVisible; // Directional navigation is visible and allowed (will handle ImGuiKey_NavXXX events). float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames 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 root windows (exclude child windows) ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. //------------------------------------------------------------------ // [Internal] ImGui will maintain those fields. Forward compatibility not guaranteed! //------------------------------------------------------------------ ImVec2 MousePosPrev; // Previous mouse position temporary storage (nb: not for public use, set to MousePos in NewFrame()) ImVec2 MouseClickedPos[5]; // Position at time of clicking float MouseClickedTime[5]; // Time of last click (used to figure out double-click) bool MouseClicked[5]; // Mouse button went from !Down to Down 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 ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking 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 float NavInputsDownDuration[ImGuiNavInput_COUNT]; float NavInputsDownDurationPrev[ImGuiNavInput_COUNT]; IMGUI_API ImGuiIO(); }; //----------------------------------------------------------------------------- // Obsolete functions (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { // OBSOLETED in 1.60 (from Dec 2017) static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } static inline ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = 0.f) { (void)on_edge; (void)outward; IM_ASSERT(0); return pos; } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) static inline void ShowTestWindow() { return ShowDemoWindow(); } static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); } static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); } static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); } static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha_override = -1.0f, ImGuiWindowFlags flags = 0); // Use SetNextWindowSize(size, ImGuiCond_FirstUseEver) + SetNextWindowBgAlpha() instead. static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); } static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } static inline void SetNextWindowPosCenter(ImGuiCond c=0) { ImGuiIO& io = GetIO(); SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), c, ImVec2(0.5f, 0.5f)); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); } static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // This was misleading and partly broken. You probably want to use the ImGui::GetIO().WantCaptureMouse flag instead. static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } // OBSOLETED IN 1.49 (between Apr 2016 and May 2016) 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)); } } #endif //----------------------------------------------------------------------------- // 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/destructors. This is intentional and we do not require it. Do not use this class as a straight std::vector replacement in your code! template class ImVector { public: int Size; int Capacity; T* Data; typedef T value_type; typedef value_type* iterator; typedef const value_type* const_iterator; inline ImVector() { Size = Capacity = 0; Data = NULL; } inline ~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& 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 sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; } inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } inline void resize(int new_size, const T& v){ if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) Data[n] = v; 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(T)); if (Data) memcpy(new_data, Data, (size_t)Size * sizeof(T)); ImGui::MemFree(Data); Data = new_data; Capacity = new_capacity; } // NB: &v cannot be pointing inside the ImVector Data itself! e.g. v.push_back(v[10]) is forbidden. 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 void push_front(const value_type& v) { if (Size == 0) push_back(v); else insert(Data, v); } 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(_grow_capacity(Size + 1)); 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; } inline bool contains(const value_type& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; } }; // 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: // static ImGuiOnceUponAFrame oaf; // if (oaf) // ImGui::Text("This will be called only once per frame"); 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 macro for ImGuiOnceUponAFrame. Attention: The macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Will obsolete #define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf; if (imgui_oaf) #endif // 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& out); }; char InputBuf[256]; ImVector Filters; int CountGrep; IMGUI_API ImGuiTextFilter(const char* default_filter = ""); IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; IMGUI_API void Build(); void Clear() { InputBuf[0] = 0; Build(); } bool IsActive() const { return !Filters.empty(); } }; // Helper: Text buffer for logging/accumulating text struct ImGuiTextBuffer { ImVector 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); } void reserve(int capacity) { Buf.reserve(capacity); } const char* c_str() const { return Buf.Data; } IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2); IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2); }; // Helper: Simple Key->value storage // Typically you don't have to worry about this since a storage is held within each Window. // We use it to e.g. store collapse state for a tree (Int 0/1), store color edit options. // This is optimized for efficient reading (dichotomy into a contiguous buffer), rare writing (typically tied to user interactions) // You can use it as custom user storage for temporary values. Declare your own storage if, for example: // - 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 (probably not efficient, but convenient) // 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 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. void Clear() { Data.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 for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; 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); // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. IMGUI_API void BuildSortByKey(); }; // 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. IMGUI_API void DeleteChars(int pos, int bytes_count); IMGUI_API 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 ImGuiSizeCallbackData { 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. }; // Data payload for Drag and Drop operations struct ImGuiPayload { // Members const void* Data; // Data (copied and owned by dear imgui) int DataSize; // Data size // [Internal] ImGuiID SourceId; // Source item id ImGuiID SourceParentId; // Source parent id (if available) int DataFrameCount; // Data timestamp char DataType[12 + 1]; // Data type tag (short user-supplied string, 12 characters max) bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. ImGuiPayload() { Clear(); } void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; } bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; } bool IsPreview() const { return Preview; } bool IsDelivery() const { return Delivery; } }; // 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 #define IM_COL32_A_MASK 0xFF000000 #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 #define IM_COL32_A_MASK 0xFF000000 #endif #define IM_COL32(R,G,B,A) (((ImU32)(A)<>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; } // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. 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 GetFrameHeightWithSpacing(). // 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 = ClipRect.z = ClipRect.w = 0.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) // NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. 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 CmdBuffer; ImVector IdxBuffer; }; enum ImDrawCornerFlags_ { ImDrawCornerFlags_TopLeft = 1 << 0, // 0x1 ImDrawCornerFlags_TopRight = 1 << 1, // 0x2 ImDrawCornerFlags_BotLeft = 1 << 2, // 0x4 ImDrawCornerFlags_BotRight = 1 << 3, // 0x8 ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, // 0x3 ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, // 0xC ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, // 0x5 ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, // 0xA ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience }; enum ImDrawListFlags_ { ImDrawListFlags_AntiAliasedLines = 1 << 0, ImDrawListFlags_AntiAliasedFill = 1 << 1 }; // 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. // Each ImGui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to access the current window draw list and draw custom primitives. // You can interleave normal ImGui:: calls and adding primitives to the current draw list. // All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), however you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well) // Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects. struct ImDrawList { // This is what you have to render ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those ImVector VtxBuffer; // Vertex buffer. // [Internal, used while building lists] ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) const char* _OwnerName; // Pointer to owner window's name 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 _ClipRectStack; // [Internal] ImVector _TextureIdStack; // [Internal] ImVector _Path; // [Internal] current path building int _ChannelsCurrent; // [Internal] current channel number (0) int _ChannelsCount; // [Internal] number of active channels (1+) ImVector _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size) // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _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(); inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } // 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_flags = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // 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& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF); IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners = ImDrawCornerFlags_All); IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col); 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 PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); PathClear(); } inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); 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_flags = ImDrawCornerFlags_All); // 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() { Clear(); } void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; } // Draw lists are owned by the ImGuiContext and only pointed to here. IMGUI_API void DeIndexAllBuffers(); // For backward compatibility or convenience: 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/OTF data int FontDataSize; // // TTF/OTF data size bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). int FontNo; // 0 // Index of font within TTF/OTF 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. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. const ImWchar* GlyphRanges; // NULL // 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). You may want to use GlyphOffset.y when merge font of different heights. unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one. float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. // [Internal] char Name[32]; // Name (strictly to ease debugging) ImFont* DstFont; IMGUI_API ImFontConfig(); }; struct ImFontGlyph { ImWchar Codepoint; // 0x0000..0xFFFF float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in) float X0, Y0, X1, Y1; // Glyph corners float U0, V0, U1, V1; // Texture coordinates }; enum ImFontAtlasFlags_ { ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas }; // Load and rasterize multiple TTF/OTF 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. // IMPORTANT: If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the ImFont is build (when calling GetTextData*** or Build()). 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* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after Build(). Set font_cfg->FontDataOwnedByAtlas to false to keep ownership. IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. 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 // Build atlas, retrieve pixel data. // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). // RGBA32 format is provided for convenience and compatibility, but note that unless you use CustomRect to draw color data, the RGB pixels emitted from Fonts will all be white (~75% of waste). // Pitch = Width * BytesPerPixels IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. 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(ImTextureID id) { TexID = id; } //------------------------------------------- // Glyph Ranges //------------------------------------------- // 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. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. 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(); // Default + 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 // Helpers to build glyph ranges from text data. Feed your application strings/characters to it then call BuildRanges(). struct GlyphRangesBuilder { ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) GlyphRangesBuilder() { UsedChars.resize(0x10000 / 8); memset(UsedChars.Data, 0, 0x10000 / 8); } bool GetBit(int n) { return (UsedChars[n >> 3] & (1 << (n & 7))) != 0; } void SetBit(int n) { UsedChars[n >> 3] |= 1 << (n & 7); } // Set bit 'c' in the array void AddChar(ImWchar c) { SetBit(c); } // Add character IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault) to force add all of ASCII/Latin+Ext IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges }; //------------------------------------------- // Custom Rectangles/Glyphs API //------------------------------------------- // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. After calling Build(), you can query the rectangle position and render your pixels. // You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. struct CustomRect { unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data. unsigned short Width, Height; // Input // Desired rectangle dimension unsigned short X, Y; // Output // Packed position in Atlas float GlyphAdvanceX; // Input // For custom font glyphs only (ID<0x10000): glyph xadvance ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID<0x10000): glyph display offset ImFont* Font; // Input // For custom font glyphs only (ID<0x10000): target font CustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } bool IsPacked() const { return X != 0xFFFF; } }; IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and ImDrawList IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x10000 to register a rectangle to map into a specific font. const CustomRect* GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } // Internals IMGUI_API void CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max); IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); //------------------------------------------- // Members //------------------------------------------- ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. 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. int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1. // [Internal] // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you. 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(). ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight) ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel ImVector 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. ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. ImVector ConfigData; // Internal data int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList }; // Font runtime data and rendering // ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). struct ImFont { // Members: Hot ~62/78 bytes float FontSize; // // 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 Glyphs; // // All glyphs. ImVector IndexAdvanceX; // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). ImVector IndexLookup; // // Sparse. Index glyphs by Unicode code-point. const ImFontGlyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) float FallbackAdvanceX; // == FallbackGlyph->AdvanceX 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] int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); IMGUI_API void ClearOutputData(); IMGUI_API void BuildLookupTable(); IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const; IMGUI_API void SetFallbackChar(ImWchar c); float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } bool IsLoaded() const { return ContainerAtlas != NULL; } const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; } // '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; // [Internal] IMGUI_API void GrowIndex(int new_size); IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); 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. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontGlyph Glyph; // OBSOLETE 1.52+ #endif }; #if defined(__clang__) #pragma clang diagnostic pop #endif // Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h) #ifdef IMGUI_INCLUDE_IMGUI_USER_H #include "imgui_user.h" #endif ================================================ FILE: ui/imgui/imgui_demo.cpp ================================================ // dear imgui, v1.60 WIP // (demo code) // Message to the person tempted to delete this file when integrating ImGui into their code base: // Don't do it! Do NOT remove this file from your project! It is useful reference code that you and other users will want to refer to. // Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow(). // During development, you can call ImGui::ShowDemoWindow() in your code to learn about various features of ImGui. Have it wired in a debug menu! // Removing this file from your project is hindering access to documentation for everyone in your team, likely leading you to poorer usage of the library. // Note that you can #define IMGUI_DISABLE_DEMO_WINDOWS in imconfig.h for the same effect. // If you want to link core ImGui in your final builds but not those demo windows, #define IMGUI_DISABLE_DEMO_WINDOWS in imconfig.h and those functions will be empty. // In other situation, when you have ImGui available you probably want this to be available for reference and execution. // Thank you, // -Your beloved friend, imgui_demo.cpp (that you won't delete) // Message to beginner C/C++ programmers. About the meaning of 'static': in this demo code, we frequently we use 'static' variables inside functions. // We do this as a way to gather code and data in the same place, just to make the demo code faster to read, faster to write, and use less code. // A static variable persist across calls, so it is essentially like a global variable but declared inside the scope of the function. // It also happens to be a convenient way of storing simple UI related information as long as your function doesn't need to be reentrant or used in threads. // This might be a pattern you occasionally want to use in your code, but most of the real data you would be editing is likely to be stored outside your function. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #include // toupper, isprint #include // sqrtf, powf, cosf, sinf, floorf, ceilf #include // vsnprintf, sscanf, printf #include // NULL, malloc, free, atoi #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include // intptr_t #else #include // 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. #if __has_warning("-Wreserved-id-macro") #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // #endif #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 #if (__GNUC__ >= 6) #pragma GCC diagnostic ignored "-Wmisleading-indentation" // warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub. #endif #endif // Play it nice with Windows users. Notepad in 2017 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_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B)) //----------------------------------------------------------------------------- // DEMO CODE //----------------------------------------------------------------------------- #if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && defined(IMGUI_DISABLE_TEST_WINDOWS) && !defined(IMGUI_DISABLE_DEMO_WINDOWS) // Obsolete name since 1.53, TEST->DEMO #define IMGUI_DISABLE_DEMO_WINDOWS #endif #if !defined(IMGUI_DISABLE_DEMO_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 ShowExampleAppWindowTitles(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(ImGui::GetFontSize() * 35.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\n(double-click to auto fit window to its contents)."); ImGui::BulletText("Click and drag on any empty space to move window."); ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text."); if (ImGui::GetIO().FontAllowUserScaling) ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); ImGui::BulletText("Mouse Wheel to scroll."); ImGui::BulletText("While editing text:\n"); ImGui::Indent(); ImGui::BulletText("Hold SHIFT or use mouse to select text."); ImGui::BulletText("CTRL+Left/Right to word jump."); ImGui::BulletText("CTRL+A or double-click to select all."); ImGui::BulletText("CTRL+X,CTRL+C,CTRL+V to use clipboard."); ImGui::BulletText("CTRL+Z,CTRL+Y to undo/redo."); ImGui::BulletText("ESCAPE to revert."); ImGui::BulletText("You can apply arithmetic operators +,*,/ on numerical values.\nUse +- to subtract."); ImGui::Unindent(); } // Demonstrate most ImGui features (big function!) void ImGui::ShowDemoWindow(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_window_titles = 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_window_titles) ShowExampleAppWindowTitles(&show_app_window_titles); 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 Dear ImGui", &show_app_about, ImGuiWindowFlags_AlwaysAutoResize); ImGui::Text("Dear ImGui, %s", ImGui::GetVersion()); ImGui::Separator(); ImGui::Text("By Omar Cornut and all dear imgui contributors."); ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information."); ImGui::End(); } static bool no_titlebar = false; static bool no_scrollbar = false; static bool no_menu = false; static bool no_move = false; static bool no_resize = false; static bool no_collapse = false; static bool no_close = false; static bool no_nav = 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_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar; if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar; if (no_move) window_flags |= ImGuiWindowFlags_NoMove; if (no_resize) window_flags |= ImGuiWindowFlags_NoResize; if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse; if (no_nav) window_flags |= ImGuiWindowFlags_NoNav; if (no_close) p_open = NULL; // Don't pass our bool* to Begin ImGui::SetNextWindowSize(ImVec2(550,680), ImGuiCond_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. (%s)", IMGUI_VERSION); // 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 titles", NULL, &show_app_window_titles); 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 Dear ImGui", NULL, &show_app_about); ImGui::EndMenu(); } ImGui::EndMenuBar(); } ImGui::Spacing(); if (ImGui::CollapsingHeader("Help")) { ImGui::TextWrapped("This window is being created by the ShowDemoWindow() function. Please refer to the code in imgui_demo.cpp for reference.\n\n"); ImGui::Text("USER GUIDE:"); ImGui::ShowUserGuide(); } if (ImGui::CollapsingHeader("Window options")) { ImGui::Checkbox("No titlebar", &no_titlebar); ImGui::SameLine(150); ImGui::Checkbox("No scrollbar", &no_scrollbar); ImGui::SameLine(300); ImGui::Checkbox("No menu", &no_menu); ImGui::Checkbox("No move", &no_move); ImGui::SameLine(150); ImGui::Checkbox("No resize", &no_resize); ImGui::SameLine(300); ImGui::Checkbox("No collapse", &no_collapse); ImGui::Checkbox("No close", &no_close); ImGui::SameLine(150); ImGui::Checkbox("No nav", &no_nav); if (ImGui::TreeNode("Style")) { ImGui::ShowStyleEditor(); ImGui::TreePop(); } if (ImGui::TreeNode("Capture/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("Basic")) { static int clicked = 0; if (ImGui::Button("Button")) clicked++; if (clicked & 1) { 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, (ImVec4)ImColor::HSV(i/7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i/7.0f, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)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 ImGuiOnceUponAFrame helper. //static ImGuiOnceUponAFrame once; //for (int i = 0; i < 5; i++) // if (once) // ImGui::Text("This will be displayed only once."); ImGui::Separator(); ImGui::LabelText("label", "Value"); { // Simplified one-liner Combo() API, using values packed in a single constant string static int current_item_1 = 1; ImGui::Combo("combo", ¤t_item_1, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); //ImGui::Combo("combo w/ array of char*", ¤t_item_2_idx, 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. // General BeginCombo() API, you have full control over your selection data and display type const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO", "PPPP", "QQQQQQQQQQ", "RRR", "SSSS" }; static const char* current_item_2 = NULL; if (ImGui::BeginCombo("combo 2", current_item_2)) // The second parameter is the label previewed before opening the combo. { for (int n = 0; n < IM_ARRAYSIZE(items); n++) { bool is_selected = (current_item_2 == items[n]); // You can store your selection however you want, outside or inside your objects if (ImGui::Selectable(items[n], is_selected)) current_item_2 = items[n]; if (is_selected) ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch) } ImGui::EndCombo(); } } { 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 open a color picker.\nRight-click on the colored square to show options.\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(); ImGui::TreePop(); } 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("button")) { }; 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(). node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "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; ImGui::Checkbox("Enable extra group", &closable_group); if (ImGui::CollapsingHeader("Header")) { ImGui::Text("IsItemHovered: %d", IsItemHovered()); for (int i = 0; i < 5; i++) ImGui::Text("Some content %d", i); } if (ImGui::CollapsingHeader("Header with a close button", &closable_group)) { ImGui::Text("IsItemHovered: %d", IsItemHovered()); 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("Text")) { 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::SameLine(); ShowHelpMarker("The TextDisabled color is stored in ImGuiStyle."); 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("The lazy dog is a good dog. This paragraph is made to fit within %.0f pixels. Testing a 1 character word. 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, c cccccccc,dddddddd. d 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) // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8 // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. Visual Studio save your file as 'UTF-8 without signature') // - HOWEVER, FOR THIS DEMO FILE, BECAUSE WE WANT TO SUPPORT COMPILER, WE ARE *NOT* INCLUDING RAW UTF-8 CHARACTERS IN THIS SOURCE FILE. // Instead we are encoding a few string with hexadecimal constants. Don't do this in your application! // Note that characters values are preserved even by InputText() 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"; // "nihongo" ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); ImGui::TreePop(); } 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!"); ImGuiIO& io = ImGui::GetIO(); // Here we are grabbing the font texture because that's the only one we have access to inside the demo code. // Remember that ImTextureID is just storage for whatever you want it to be, it is essentially a value that will be passed to the render function inside the ImDrawCmd structure. // If you use one of the default imgui_impl_XXXX.cpp renderer, they all have comments at the top of their file to specify what they expect to be stored in ImTextureID. // (for example, the imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer. The imgui_impl_glfw_gl3.cpp renderer expect a GLuint OpenGL texture identifier etc.) // If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers to ImGui::Image(), and gather width/height through your own functions, etc. // Using ShowMetricsWindow() as a "debugger" to inspect the draw data that are being passed to your render will help you debug issues if you are confused about this. // Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). ImTextureID my_tex_id = io.Fonts->TexID; float my_tex_w = (float)io.Fonts->TexWidth; float my_tex_h = (float)io.Fonts->TexHeight; ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); ImVec2 pos = ImGui::GetCursorScreenPos(); ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_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 = io.MousePos.x - pos.x - focus_sz * 0.5f; if (focus_x < 0.0f) focus_x = 0.0f; else if (focus_x > my_tex_w - focus_sz) focus_x = my_tex_w - focus_sz; float focus_y = io.MousePos.y - pos.y - focus_sz * 0.5f; if (focus_y < 0.0f) focus_y = 0.0f; else if (focus_y > my_tex_h - focus_sz) focus_y = my_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) / my_tex_w, (focus_y) / my_tex_h); ImVec2 uv1 = ImVec2((focus_x + focus_sz) / my_tex_w, (focus_y + focus_sz) / my_tex_h); ImGui::Image(my_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(my_tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/my_tex_w,32/my_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")) { // Selectable() has 2 overloads: // - The one taking "bool selected" as a read-only selection information. When Selectable() has been clicked is returns true and you can alter selection state accordingly. // - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases) // The earlier is more flexible, as in real application your selection may be stored in a different manner (in flags within objects, as an external list, etc). if (ImGui::TreeNode("Basic")) { static bool selection[5] = { false, true, false, false, false }; ImGui::Selectable("1. I am selectable", &selection[0]); ImGui::Selectable("2. I am selectable", &selection[1]); ImGui::Text("3. I am not selectable"); ImGui::Selectable("4. I am selectable", &selection[3]); if (ImGui::Selectable("5. I am double clickable", selection[4], ImGuiSelectableFlags_AllowDoubleClick)) if (ImGui::IsMouseDoubleClicked(0)) selection[4] = !selection[4]; ImGui::TreePop(); } if (ImGui::TreeNode("Selection State: Single Selection")) { static int selected = -1; for (int n = 0; n < 5; n++) { char buf[32]; sprintf(buf, "Object %d", n); if (ImGui::Selectable(buf, selected == n)) selected = n; } ImGui::TreePop(); } if (ImGui::TreeNode("Selection State: Multiple Selection")) { ShowHelpMarker("Hold CTRL and click to select multiple items."); static bool selection[5] = { false, false, false, false, false }; for (int n = 0; n < 5; n++) { char buf[32]; sprintf(buf, "Object %d", n); if (ImGui::Selectable(buf, selection[n])) { if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held memset(selection, 0, sizeof(selection)); selection[n] ^= 1; } } ImGui::TreePop(); } if (ImGui::TreeNode("Rendering more text into the same line")) { // Using the Selectable() override that takes "bool* p_selected" parameter and toggle your booleans automatically. 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(); } if (ImGui::TreeNode("Plots 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; static float refresh_time = 0.0f; if (!animate || refresh_time == 0.0f) refresh_time = ImGui::GetTime(); while (refresh_time < ImGui::GetTime()) // Create dummy data at fixed 60 hz rate for the demo { static float phase = 0.0f; values[values_offset] = cosf(phase); values_offset = (values_offset+1) % IM_ARRAYSIZE(values); phase += 0.10f*values_offset; refresh_time += 1.0f/60.0f; } 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 : -1.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); ImGui::TreePop(); } if (ImGui::TreeNode("Color/Picker Widgets")) { static ImVec4 color = ImColor(114, 144, 154, 200); static bool alpha_preview = true; static bool alpha_half_preview = false; static bool options_menu = true; static bool hdr = false; ImGui::Checkbox("With Alpha Preview", &alpha_preview); ImGui::Checkbox("With Half Alpha Preview", &alpha_half_preview); ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); ShowHelpMarker("Right-click on the individual color widget to show options."); ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); ShowHelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); int misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions); ImGui::Text("Color widget:"); ImGui::SameLine(); ShowHelpMarker("Click on the colored square to open a color picker.\nCTRL+click on individual component to input value.\n"); ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags); ImGui::Text("Color widget HSV with Alpha:"); ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_HSV | misc_flags); ImGui::Text("Color widget with Float Display:"); ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags); ImGui::Text("Color button with Picker:"); ImGui::SameLine(); ShowHelpMarker("With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\nWith the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only be used for the tooltip and picker popup."); ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags); ImGui::Text("Color button with Custom Picker Popup:"); // Generate a dummy palette static bool saved_palette_inited = false; static ImVec4 saved_palette[32]; if (!saved_palette_inited) for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) { ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, saved_palette[n].x, saved_palette[n].y, saved_palette[n].z); saved_palette[n].w = 1.0f; // Alpha } saved_palette_inited = true; static ImVec4 backup_color; bool open_popup = ImGui::ColorButton("MyColor##3b", color, misc_flags); ImGui::SameLine(); open_popup |= ImGui::Button("Palette"); if (open_popup) { ImGui::OpenPopup("mypicker"); backup_color = color; } if (ImGui::BeginPopup("mypicker")) { // FIXME: Adding a drag and drop example here would be perfect! ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!"); ImGui::Separator(); ImGui::ColorPicker4("##picker", (float*)&color, misc_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview); ImGui::SameLine(); ImGui::BeginGroup(); ImGui::Text("Current"); ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60,40)); ImGui::Text("Previous"); if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60,40))) color = backup_color; ImGui::Separator(); ImGui::Text("Palette"); for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) { ImGui::PushID(n); if ((n % 8) != 0) ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); if (ImGui::ColorButton("##palette", saved_palette[n], ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip, ImVec2(20,20))) color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3); if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4); EndDragDropTarget(); } ImGui::PopID(); } ImGui::EndGroup(); ImGui::EndPopup(); } ImGui::Text("Color button only:"); ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags, ImVec2(80,80)); ImGui::Text("Color picker:"); static bool alpha = true; static bool alpha_bar = true; static bool side_preview = true; static bool ref_color = false; static ImVec4 ref_color_v(1.0f,0.0f,1.0f,0.5f); static int inputs_mode = 2; static int picker_mode = 0; ImGui::Checkbox("With Alpha", &alpha); ImGui::Checkbox("With Alpha Bar", &alpha_bar); ImGui::Checkbox("With Side Preview", &side_preview); if (side_preview) { ImGui::SameLine(); ImGui::Checkbox("With Ref Color", &ref_color); if (ref_color) { ImGui::SameLine(); ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags); } } ImGui::Combo("Inputs Mode", &inputs_mode, "All Inputs\0No Inputs\0RGB Input\0HSV Input\0HEX Input\0"); ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0Hue bar + SV rect\0Hue wheel + SV triangle\0"); ImGui::SameLine(); ShowHelpMarker("User can right-click the picker to change mode."); ImGuiColorEditFlags flags = misc_flags; if (!alpha) flags |= ImGuiColorEditFlags_NoAlpha; // This is by default if you call ColorPicker3() instead of ColorPicker4() if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar; if (!side_preview) flags |= ImGuiColorEditFlags_NoSidePreview; if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar; if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel; if (inputs_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; if (inputs_mode == 2) flags |= ImGuiColorEditFlags_RGB; if (inputs_mode == 3) flags |= ImGuiColorEditFlags_HSV; if (inputs_mode == 4) flags |= ImGuiColorEditFlags_HEX; ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL); ImGui::Text("Programmatically set defaults/options:"); ImGui::SameLine(); ShowHelpMarker("SetColorEditOptions() is designed to allow you to set boot-time default.\nWe don't have Push/Pop functions because you can force options on a per-widget basis if needed, and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid encouraging you to persistently save values that aren't forward-compatible."); if (ImGui::Button("Uint8 + HSV")) ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_HSV); ImGui::SameLine(); if (ImGui::Button("Float + HDR")) ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_RGB); ImGui::TreePop(); } if (ImGui::TreeNode("Range Widgets")) { 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::TreePop(); } if (ImGui::TreeNode("Multi-component Widgets")) { 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::TreePop(); } if (ImGui::TreeNode("Vertical Sliders")) { 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, (ImVec4)ImColor::HSV(i/7.0f, 0.5f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i/7.0f, 0.6f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i/7.0f, 0.7f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)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::TreePop(); } } if (ImGui::CollapsingHeader("Layout")) { if (ImGui::TreeNode("Child regions")) { static bool disable_mouse_wheel = false; static bool disable_menu = false; ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel); ImGui::Checkbox("Disable Menu", &disable_menu); 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(); // Child 1: no border, enable horizontal scrollbar { ImGui::BeginChild("Child1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 300), false, ImGuiWindowFlags_HorizontalScrollbar | (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0)); 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(); // Child 2: rounded border { ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); ImGui::BeginChild("Child2", ImVec2(0,300), true, (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0) | (disable_menu ? 0 : ImGuiWindowFlags_MenuBar)); if (!disable_menu && ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Menu")) { ShowExampleMenuFile(); ImGui::EndMenu(); } ImGui::EndMenuBar(); } 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::AlignTextToFramePadding(); 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(); ImGui::SameLine(); ImGui::Button("EEE"); ImGui::EndGroup(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("First group hovered"); } // 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::AlignTextToFramePadding(); // 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"); ImGui::SameLine(); ImGui::Button("Widget##3"); // 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::AlignTextToFramePadding(); // 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::AlignTextToFramePadding(); 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 Pos"); 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); } } float scroll_y = ImGui::GetScrollY(), scroll_max_y = ImGui::GetScrollMaxY(); ImGui::EndChild(); ImGui::Text("%.0f/%0.f", scroll_y, scroll_max_y); 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::GetFrameHeightWithSpacing()*7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar); for (int line = 0; line < lines; line++) { // Display random stuff (for the sake of this trivial demo we are using basic Button+SameLine. If you want to create your own time line for a real application you may be better off // manipulating the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets yourself. You may also want to use the lower-level ImDrawList API) 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]; sprintf(num_buf, "%d", n); const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : num_buf; float hue = n*0.05f; ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)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(); } } float scroll_x = ImGui::GetScrollX(), scroll_max_x = ImGui::GetScrollMaxX(); 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; ImGui::SameLine(); ImGui::Text("%.0f/%.0f", scroll_x, scroll_max_x); 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), IM_COL32(90,90,120,255)); ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x+offset.x,pos.y+offset.y), IM_COL32(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 }; // Simple selection popup // (If you want to show the current selection inside the Button itself, you may want to build a string using the "###" operator to preserve a constant ID with a variable label) if (ImGui::Button("Select..")) ImGui::OpenPopup("select"); ImGui::SameLine(); ImGui::TextUnformatted(selected_fish == -1 ? "" : 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(); } // Showing a menu with toggles 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("FilePopup"); if (ImGui::BeginPopup("FilePopup")) { ShowExampleMenuFile(); ImGui::EndPopup(); } ImGui::TreePop(); } if (ImGui::TreeNode("Context menus")) { // BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing: // if (IsItemHovered() && IsMouseClicked(0)) // OpenPopup(id); // return BeginPopup(id); // For more advanced uses you may want to replicate and cuztomize this code. This the comments inside BeginPopupContextItem() implementation. 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::PushItemWidth(-1); ImGui::DragFloat("##Value", &value, 0.1f, 0.0f, 0.0f); ImGui::PopItemWidth(); ImGui::EndPopup(); } static char name[32] = "Label1"; char buf[64]; sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label ImGui::Button(buf); if (ImGui::BeginPopupContextItem()) // When used after an item that has an ID (here the Button), we can skip providing an ID to BeginPopupContextItem(). { ImGui::Text("Edit name:"); ImGui::InputText("##edit", name, IM_ARRAYSIZE(name)); 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::SetItemDefaultFocus(); 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\nUsing style.Colors[ImGuiCol_ModalWindowDarkening] for darkening."); static int item = 1; ImGui::Combo("Combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); static float color[4] = { 0.4f,0.7f,0.0f,0.5f }; ImGui::ColorEdit4("color", color); // This is to test behavior of stacked regular popups over a modal if (ImGui::Button("Add another modal..")) 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::TreeNode("Menus inside a regular window")) { 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::CollapsingHeader("Columns")) { ImGui::PushID("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("Hovered"); 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; bool hovered = ImGui::IsItemHovered(); ImGui::NextColumn(); ImGui::Text(names[i]); ImGui::NextColumn(); ImGui::Text(paths[i]); ImGui::NextColumn(); ImGui::Text("%d", hovered); ImGui::NextColumn(); } ImGui::Columns(1); ImGui::Separator(); 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")) { // NB: Future columns API should allow automatic horizontal 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); for (int i = 0; i < 4*3; i++) { if (h_borders && ImGui::GetColumnIndex() == 0) ImGui::Separator(); ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); ImGui::Text("Width %.2f\nOffset %.2f", ImGui::GetColumnWidth(), ImGui::GetColumnOffset()); ImGui::NextColumn(); } ImGui::Columns(1); if (h_borders) ImGui::Separator(); ImGui::TreePop(); } // Scrolling columns /* if (ImGui::TreeNode("Vertical 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(); } */ if (ImGui::TreeNode("Horizontal Scrolling")) { ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f)); ImGui::BeginChild("##ScrollingRegion", ImVec2(0, ImGui::GetFontSize() * 20), false, ImGuiWindowFlags_HorizontalScrollbar); ImGui::Columns(10); int ITEMS_COUNT = 2000; ImGuiListClipper clipper(ITEMS_COUNT); // Also demonstrate using the clipper for large list while (clipper.Step()) { for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) for (int j = 0; j < 10; j++) { ImGui::Text("Line %d Column %d...", i, j); ImGui::NextColumn(); } } ImGui::Columns(1); ImGui::EndChild(); ImGui::TreePop(); } bool node_open = ImGui::TreeNode("Tree within single cell"); ImGui::SameLine(); ShowHelpMarker("NB: Tree node must be poped before ending the cell. There'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(); } ImGui::PopID(); } 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("Inputs, Navigation & Focus")) { ImGuiIO& io = ImGui::GetIO(); ImGui::Text("WantCaptureMouse: %d", io.WantCaptureMouse); ImGui::Text("WantCaptureKeyboard: %d", io.WantCaptureKeyboard); ImGui::Text("WantTextInput: %d", io.WantTextInput); ImGui::Text("WantMoveMouse: %d", io.WantMoveMouse); ImGui::Text("NavActive: %d, NavVisible: %d", io.NavActive, io.NavVisible); ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor); ImGui::SameLine(); ShowHelpMarker("Request ImGui to render a mouse cursor for you in software. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something)."); ImGui::CheckboxFlags("io.NavFlags: EnableGamepad", (unsigned int *)&io.NavFlags, ImGuiNavFlags_EnableGamepad); ImGui::CheckboxFlags("io.NavFlags: EnableKeyboard", (unsigned int *)&io.NavFlags, ImGuiNavFlags_EnableKeyboard); ImGui::CheckboxFlags("io.NavFlags: MoveMouse", (unsigned int *)&io.NavFlags, ImGuiNavFlags_MoveMouse); ImGui::SameLine(); ShowHelpMarker("Request ImGui to move your move cursor when using gamepad/keyboard navigation. NewFrame() will change io.MousePos and set the io.WantMoveMouse flag, your backend will need to apply the new mouse position."); if (ImGui::TreeNode("Keyboard, Mouse & Navigation State")) { if (ImGui::IsMousePosValid()) ImGui::Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y); else ImGui::Text("Mouse pos: "); 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("Mouse wheel: %.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("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); ImGui::Text("NavInputs down:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputs[i] > 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputs[i]); } ImGui::Text("NavInputs pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] == 0.0f) { ImGui::SameLine(); ImGui::Text("[%d]", i); } ImGui::Text("NavInputs duration:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputsDownDuration[i]); } 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("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: "); // Use >= 0 parameter to SetKeyboardFocusHere() to focus an upcoming item static float f3[3] = { 0.0f, 0.0f, 0.0f }; int focus_ahead = -1; if (ImGui::Button("Focus on X")) focus_ahead = 0; ImGui::SameLine(); if (ImGui::Button("Focus on Y")) focus_ahead = 1; ImGui::SameLine(); if (ImGui::Button("Focus on Z")) focus_ahead = 2; if (focus_ahead != -1) ImGui::SetKeyboardFocusHere(focus_ahead); ImGui::SliderFloat3("Float3", &f3[0], 0.0f, 1.0f); ImGui::TextWrapped("NB: Cursor & selection are preserved when refocusing last used item in code."); ImGui::TreePop(); } if (ImGui::TreeNode("Focused & Hovered Test")) { static bool embed_all_inside_a_child_window = false; ImGui::Checkbox("Embed everything inside a child window (for additional testing)", &embed_all_inside_a_child_window); if (embed_all_inside_a_child_window) ImGui::BeginChild("embeddingchild", ImVec2(0, ImGui::GetFontSize() * 25), true); // Testing IsWindowFocused() function with its various flags (note that the flags can be combined) ImGui::BulletText( "IsWindowFocused() = %d\n" "IsWindowFocused(_ChildWindows) = %d\n" "IsWindowFocused(_ChildWindows|_RootWindow) = %d\n" "IsWindowFocused(_RootWindow) = %d\n" "IsWindowFocused(_AnyWindow) = %d\n", ImGui::IsWindowFocused(), ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows), ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow), ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow), ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)); // Testing IsWindowHovered() function with its various flags (note that the flags can be combined) ImGui::BulletText( "IsWindowHovered() = %d\n" "IsWindowHovered(_AllowWhenBlockedByPopup) = %d\n" "IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n" "IsWindowHovered(_ChildWindows) = %d\n" "IsWindowHovered(_ChildWindows|_RootWindow) = %d\n" "IsWindowHovered(_RootWindow) = %d\n" "IsWindowHovered(_AnyWindow) = %d\n", ImGui::IsWindowHovered(), ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup), ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows), ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow), ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow), ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)); // Testing IsItemHovered() function (because BulletText is an item itself and that would affect the output of IsItemHovered, we pass all lines in a single items to shorten the code) ImGui::Button("ITEM"); ImGui::BulletText( "IsItemHovered() = %d\n" "IsItemHovered(_AllowWhenBlockedByPopup) = %d\n" "IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\n" "IsItemHovered(_AllowWhenOverlapped) = %d\n" "IsItemhovered(_RectOnly) = %d\n", ImGui::IsItemHovered(), ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup), ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlapped), ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly)); ImGui::BeginChild("child", ImVec2(0,50), true); ImGui::Text("This is another child window for testing IsWindowHovered() flags."); ImGui::EndChild(); if (embed_all_inside_a_child_window) EndChild(); ImGui::TreePop(); } if (ImGui::TreeNode("Dragging")) { ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget."); for (int button = 0; button < 3; button++) ImGui::Text("IsMouseDragging(%d):\n w/ default threshold: %d,\n w/ zero threshold: %d\n w/ large threshold: %d", button, ImGui::IsMouseDragging(button), ImGui::IsMouseDragging(button, 0.0f), ImGui::IsMouseDragging(button, 20.0f)); 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(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); draw_list->PopClipRect(); // Drag operations gets "unlocked" when the mouse has moved past a certain threshold (the default threshold is stored in io.MouseDragThreshold) // You can request a lower or higher threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta() ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); ImVec2 mouse_delta = io.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("Mouse cursors")) { const char* mouse_cursors_names[] = { "Arrow", "TextInput", "Move", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE" }; IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_Count_); ImGui::Text("Current mouse cursor = %d: %s", ImGui::GetMouseCursor(), mouse_cursors_names[ImGui::GetMouseCursor()]); ImGui::Text("Hover to see mouse cursors:"); ImGui::SameLine(); ShowHelpMarker("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, otherwise your backend needs to handle it."); for (int i = 0; i < ImGuiMouseCursor_Count_; i++) { char label[32]; sprintf(label, "Mouse cursor %d: %s", i, mouse_cursors_names[i]); ImGui::Bullet(); ImGui::Selectable(label, false); if (ImGui::IsItemHovered() || ImGui::IsItemFocused()) ImGui::SetMouseCursor(i); } ImGui::TreePop(); } } ImGui::End(); } // Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. // Here we use the simplified Combo() api that packs items into a single literal string. Useful for quick combo boxes where the choices are known locally. bool ImGui::ShowStyleSelector(const char* label) { static int style_idx = -1; if (ImGui::Combo(label, &style_idx, "Classic\0Dark\0Light\0")) { switch (style_idx) { case 0: ImGui::StyleColorsClassic(); break; case 1: ImGui::StyleColorsDark(); break; case 2: ImGui::StyleColorsLight(); break; } return true; } return false; } // Demo helper function to select among loaded fonts. // Here we use the regular BeginCombo()/EndCombo() api which is more the more flexible one. void ImGui::ShowFontSelector(const char* label) { ImGuiIO& io = ImGui::GetIO(); ImFont* font_current = ImGui::GetFont(); if (ImGui::BeginCombo(label, font_current->GetDebugName())) { for (int n = 0; n < io.Fonts->Fonts.Size; n++) if (ImGui::Selectable(io.Fonts->Fonts[n]->GetDebugName(), io.Fonts->Fonts[n] == font_current)) io.FontDefault = io.Fonts->Fonts[n]; ImGui::EndCombo(); } ImGui::SameLine(); ShowHelpMarker( "- Load additional fonts with io.Fonts->AddFontFromFileTTF().\n" "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n" "- Read FAQ and documentation in misc/fonts/ for more details.\n" "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); } void ImGui::ShowStyleEditor(ImGuiStyle* ref) { // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to an internally stored reference) ImGuiStyle& style = ImGui::GetStyle(); static ImGuiStyle ref_saved_style; // Default to using internal storage as reference static bool init = true; if (init && ref == NULL) ref_saved_style = style; init = false; if (ref == NULL) ref = &ref_saved_style; ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f); if (ImGui::ShowStyleSelector("Colors##Selector")) ref_saved_style = style; ImGui::ShowFontSelector("Fonts##Selector"); // Simplified Settings if (ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding { bool window_border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &window_border)) style.WindowBorderSize = window_border ? 1.0f : 0.0f; } ImGui::SameLine(); { bool frame_border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &frame_border)) style.FrameBorderSize = frame_border ? 1.0f : 0.0f; } ImGui::SameLine(); { bool popup_border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &popup_border)) style.PopupBorderSize = popup_border ? 1.0f : 0.0f; } // Save/Revert button if (ImGui::Button("Save Ref")) *ref = ref_saved_style = style; ImGui::SameLine(); if (ImGui::Button("Revert Ref")) style = *ref; ImGui::SameLine(); ShowHelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. Use \"Export Colors\" below to save them somewhere."); if (ImGui::TreeNode("Rendering")) { ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); ImGui::SameLine(); ShowHelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); 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("PopupRounding", &style.PopupRounding, 0.0f, 16.0f, "%.0f"); ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.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("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); ImGui::Text("BorderSize"); ImGui::SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::Text("Rounding"); ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 14.0f, "%.0f"); ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 16.0f, "%.0f"); ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.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 = true; if (ImGui::Button("Export Unsaved")) { if (output_dest == 0) ImGui::LogToClipboard(); else ImGui::LogToTTY(); ImGui::LogText("ImVec4* colors = ImGui::GetStyle().Colors;" IM_NEWLINE); for (int i = 0; i < ImGuiCol_COUNT; i++) { const ImVec4& col = style.Colors[i]; const char* name = ImGui::GetStyleColorName(i); if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 23-(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 Colors", &output_only_modified); ImGui::Text("Tip: Left-click on colored square to open color picker,\nRight-click to open edit options menu."); static ImGuiTextFilter filter; filter.Draw("Filter colors", 200); static ImGuiColorEditFlags alpha_flags = 0; ImGui::RadioButton("Opaque", &alpha_flags, 0); ImGui::SameLine(); ImGui::RadioButton("Alpha", &alpha_flags, ImGuiColorEditFlags_AlphaPreview); ImGui::SameLine(); ImGui::RadioButton("Both", &alpha_flags, ImGuiColorEditFlags_AlphaPreviewHalf); ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened); ImGui::PushItemWidth(-160); for (int i = 0; i < ImGuiCol_COUNT; i++) { const char* name = ImGui::GetStyleColorName(i); if (!filter.PassFilter(name)) continue; ImGui::PushID(i); ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags); if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0) { // Tips: in a real user application, you may want to merge and use an icon font into the main font, so instead of "Save"/"Revert" you'd use icons. // Read the FAQ and misc/fonts/README.txt about using icon fonts. It's really easy and super convenient! ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) style.Colors[i] = ref->Colors[i]; } ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); ImGui::TextUnformatted(name); ImGui::PopID(); } ImGui::PopItemWidth(); ImGui::EndChild(); ImGui::TreePop(); } bool fonts_opened = ImGui::TreeNode("Fonts", "Fonts (%d)", ImGui::GetIO().Fonts->Fonts.Size); if (fonts_opened) { 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::PushID(font); bool font_details_opened = ImGui::TreeNode(font, "Font %d: \'%s\', %.2f px, %d glyphs", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size); ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) ImGui::GetIO().FontDefault = font; if (font_details_opened) { ImGui::PushFont(font); ImGui::Text("The quick brown fox jumps over the lazy dog"); ImGui::PopFont(); ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font ImGui::InputFloat("Font offset", &font->DisplayOffset.y, 1, 1, 0); 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); ImGui::Text("Texture surface: %d pixels (approx) ~ %dx%d", font->MetricsTotalSurface, (int)sqrtf((float)font->MetricsTotalSurface), (int)sqrtf((float)font->MetricsTotalSurface)); for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) { ImFontConfig* cfg = &font->ConfigData[config_i]; ImGui::BulletText("Input %d: \'%s\', Oversample: (%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 ImFontGlyph* 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 ImFontGlyph* 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("AdvanceX: %.1f", glyph->AdvanceX); 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::PopID(); } 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(); } // Demonstrate creating a fullscreen menu bar and populating it. 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; static bool b = true; ImGui::SliderFloat("Value", &f, 0.0f, 1.0f); ImGui::InputFloat("Input", &f, 0.1f); ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0"); ImGui::Checkbox("Check", &b); ImGui::EndMenu(); } if (ImGui::BeginMenu("Colors")) { float sz = ImGui::GetTextLineHeight(); for (int i = 0; i < ImGuiCol_COUNT; i++) { const char* name = ImGui::GetStyleColorName((ImGuiCol)i); ImVec2 p = ImGui::GetCursorScreenPos(); ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x+sz, p.y+sz), ImGui::GetColorU32((ImGuiCol)i)); ImGui::Dummy(ImVec2(sz, sz)); ImGui::SameLine(); ImGui::MenuItem(name); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Disabled", false)) // Disabled { IM_ASSERT(0); } if (ImGui::MenuItem("Checked", NULL, true)) {} if (ImGui::MenuItem("Quit", "Alt+F4")) {} } // Demonstrate creating a window which gets auto-resized according to its content. 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(); } // Demonstrate creating a window with custom resize constraints. static void ShowExampleAppConstrainedResize(bool* p_open) { struct CustomConstraints // Helper functions to demonstrate programmatic constraints { static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); } static void Step(ImGuiSizeCallbackData* 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 bool auto_resize = false; static int type = 0; static int display_lines = 10; 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(400, -1), ImVec2(500, -1)); // Width 400-500 if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, 500)); // Height 400-500 if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square if (type == 6) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)100);// Fixed Step ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0; if (ImGui::Begin("Example: Constrained Resize", p_open, flags)) { const char* desc[] = { "Resize vertical only", "Resize horizontal only", "Width > 100, Height > 100", "Width 400-500", "Height 400-500", "Custom: Always Square", "Custom: Fixed Steps (100)", }; 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)); } ImGui::PushItemWidth(200); ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc)); ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100); ImGui::PopItemWidth(); ImGui::Checkbox("Auto-resize", &auto_resize); for (int i = 0; i < display_lines; i++) ImGui::Text("%*sHello, sailor! Making this line long enough for the example.", i * 4, ""); } ImGui::End(); } // Demonstrate creating a simple static window with no decoration + a context-menu to choose which corner of the screen to use. static void ShowExampleAppFixedOverlay(bool* p_open) { const float DISTANCE = 10.0f; static int corner = 0; ImVec2 window_pos = ImVec2((corner & 1) ? ImGui::GetIO().DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? ImGui::GetIO().DisplaySize.y - DISTANCE : DISTANCE); ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f); ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); ImGui::SetNextWindowBgAlpha(0.3f); // Transparent background if (ImGui::Begin("Example: Fixed Overlay", p_open, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoFocusOnAppearing|ImGuiWindowFlags_NoNav)) { ImGui::Text("Simple overlay\nin the corner of the screen.\n(right-click to change position)"); ImGui::Separator(); ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); if (ImGui::BeginPopupContextWindow()) { if (ImGui::MenuItem("Top-left", NULL, corner == 0)) corner = 0; if (ImGui::MenuItem("Top-right", NULL, corner == 1)) corner = 1; if (ImGui::MenuItem("Bottom-left", NULL, corner == 2)) corner = 2; if (ImGui::MenuItem("Bottom-right", NULL, corner == 3)) corner = 3; if (p_open && ImGui::MenuItem("Close")) *p_open = false; ImGui::EndPopup(); } ImGui::End(); } } // Demonstrate using "##" and "###" in identifiers to manipulate ID generation. // This apply to regular items as well. Read FAQ section "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." for details. static void ShowExampleAppWindowTitles(bool*) { // By default, Windows are uniquely identified by their title. // You can use the "##" and "###" markers to manipulate the display/ID. // Using "##" to display same title but have unique identifier. ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiCond_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), ImGuiCond_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], ImGui::GetFrameCount()); ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiCond_FirstUseEver); ImGui::Begin(buf); ImGui::Text("This window has a changing title."); ImGui::End(); } // Demonstrate using the low-level ImDrawList to draw custom shapes. static void ShowExampleAppCustomRendering(bool* p_open) { ImGui::SetNextWindowSize(ImVec2(350,560), ImGuiCond_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, ImDrawCornerFlags_All, thickness); x += sz+spacing; draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_All, thickness); x += sz+spacing; draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotRight, 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->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotRight); 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), IM_COL32(0,0,0,255), IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255)); ImGui::Dummy(ImVec2((sz+spacing)*8, (sz+spacing)*3)); } ImGui::Separator(); { static ImVector 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), IM_COL32(50,50,50,255), IM_COL32(50,50,60,255), IM_COL32(60,60,70,255), IM_COL32(50,50,60,255)); draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(255,255,255,255)); bool adding_preview = false; ImGui::InvisibleButton("canvas", canvas_size); ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); if (adding_line) { adding_preview = true; points.push_back(mouse_pos_in_canvas); if (!ImGui::IsMouseDown(0)) adding_line = adding_preview = false; } if (ImGui::IsItemHovered()) { if (!adding_line && ImGui::IsMouseClicked(0)) { points.push_back(mouse_pos_in_canvas); adding_line = true; } 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), true); // 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(); } // Demonstrating creating a simple console window, with scrolling, filtering, completion and history. // 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 Items; bool ScrollToBottom; ImVector History; int HistoryPos; // -1: new line, 0..History.Size-1 browsing history. ImVector 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_FMTARGS(2) { // FIXME-OPT 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), ImGuiCond_FirstUseEver); if (!ImGui::Begin(title, p_open)) { ImGui::End(); return; } // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. So e.g. IsItemHovered() will return true when hovering the title bar. // Here we create a context menu only available from the title bar. if (ImGui::BeginPopupContextItem()) { if (ImGui::MenuItem("Close")) *p_open = false; ImGui::EndPopup(); } 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(); bool copy_to_clipboard = ImGui::SmallButton("Copy"); 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(); const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); // 1 separator, 1 input text ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar); // Leave room for 1 separator + 1 InputText 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 if (copy_to_clipboard) ImGui::LogToClipboard(); ImVec4 col_default_text = ImGui::GetStyleColorVec4(ImGuiCol_Text); for (int i = 0; i < Items.Size; i++) { const char* item = Items[i]; if (!filter.PassFilter(item)) continue; ImVec4 col = col_default_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 (copy_to_clipboard) ImGui::LogFinish(); if (ScrollToBottom) ImGui::SetScrollHere(); ScrollToBottom = false; ImGui::PopStyleVar(); ImGui::EndChild(); ImGui::Separator(); // Command-line bool reclaim_focus = false; 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, ""); reclaim_focus = true; } // Demonstrate keeping focus on the input box ImGui::SetItemDefaultFocus(); if (reclaim_focus) 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) { int first = History.Size - 10; for (int i = first > 0 ? first : 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 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 == 0 || 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 LineOffsets; // Index to lines offset bool ScrollToBottom; void Clear() { Buf.clear(); LineOffsets.clear(); } void AddLog(const char* fmt, ...) IM_FMTARGS(2) { int old_size = Buf.size(); va_list args; va_start(args, fmt); Buf.appendfv(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), ImGuiCond_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(); } }; // Demonstrate creating a simple log window with basic filtering. static void ShowExampleAppLog(bool* p_open) { static ExampleAppLog log; // Demo: add random items (unless Ctrl is held) static float last_time = -1.0f; float time = ImGui::GetTime(); if (time - last_time >= 0.20f && !ImGui::GetIO().KeyCtrl) { const char* random_words[] = { "system", "info", "warning", "error", "fatal", "notice", "log" }; log.AddLog("[%s] Hello, time is %.1f, frame count is %d\n", random_words[rand() % IM_ARRAYSIZE(random_words)], time, ImGui::GetFrameCount()); last_time = time; } log.Draw("Example: Log", p_open); } // Demonstrate create a window with multiple child windows. static void ShowExampleAppLayout(bool* p_open) { ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiCond_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::GetFrameHeightWithSpacing())); // 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(); if (ImGui::Button("Revert")) {} ImGui::SameLine(); if (ImGui::Button("Save")) {} ImGui::EndGroup(); } ImGui::End(); } // Demonstrate create a simple property editor. static void ShowExampleAppPropertyEditor(bool* p_open) { ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiCond_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::AlignTextToFramePadding(); // 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::AlignTextToFramePadding(); 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::AlignTextToFramePadding(); // 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(); } // Demonstrate/test rendering huge amount of text, and the incidence of clipping. static void ShowExampleAppLongText(bool* p_open) { ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiCond_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 (slow)\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.appendf("%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::ShowDemoWindow(bool*) {} void ImGui::ShowUserGuide() {} void ImGui::ShowStyleEditor(ImGuiStyle*) {} #endif ================================================ FILE: ui/imgui/imgui_draw.cpp ================================================ // dear imgui, v1.60 WIP // (drawing and font code) // Contains implementation for // - Default styles // - 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 #include "imgui_internal.h" #include // vsnprintf, sscanf, printf #if !defined(alloca) #ifdef _WIN32 #include // alloca #if !defined(alloca) #define alloca _alloca // for clang with MS Codegen #endif #elif defined(__GLIBC__) || defined(__sun) #include // alloca #else #include // 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 // #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" // warning : possible misuse of comma operator here // #endif #if __has_warning("-Wreserved-id-macro") #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // #endif #if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #endif #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 #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers #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 "-Wunused-function" #pragma clang diagnostic ignored "-Wmissing-prototypes" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #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 //----------------------------------------------------------------------------- // Style functions //----------------------------------------------------------------------------- void ImGui::StyleColorsDark(ImGuiStyle* dst) { ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); ImVec4* colors = style->Colors; colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f); colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f); colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f); colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f); colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_Separator] = colors[ImGuiCol_Border]; colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.25f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); colors[ImGuiCol_CloseButton] = ImVec4(0.41f, 0.41f, 0.41f, 0.50f); colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); 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.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); } void ImGui::StyleColorsClassic(ImGuiStyle* dst) { ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); ImVec4* colors = style->Colors; colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 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_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_PopupBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f); colors[ImGuiCol_Border] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.47f, 0.47f, 0.69f, 0.40f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.42f, 0.41f, 0.64f, 0.69f); colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); 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.41f, 0.39f, 0.80f, 0.60f); colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); colors[ImGuiCol_SliderGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f); colors[ImGuiCol_Button] = ImVec4(0.35f, 0.40f, 0.61f, 0.62f); colors[ImGuiCol_ButtonHovered] = ImVec4(0.40f, 0.48f, 0.71f, 0.79f); colors[ImGuiCol_ButtonActive] = ImVec4(0.46f, 0.54f, 0.80f, 1.00f); colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.16f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f); colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f); colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f); colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); 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_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); } // Those light colors are better suited with a thicker font than the default one + FrameBorder void ImGui::StyleColorsLight(ImGuiStyle* dst) { ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); ImVec4* colors = style->Colors; colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); //colors[ImGuiCol_TextHovered] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); //colors[ImGuiCol_TextActive] = ImVec4(1.00f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_WindowBg] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f); colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_PopupBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f); colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.30f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f); colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f); colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f); colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f); colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.49f, 0.49f, 0.49f, 0.80f); colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f); colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_SliderGrab] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f); colors[ImGuiCol_SliderGrabActive] = ImVec4(0.46f, 0.54f, 0.80f, 0.60f); colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(0.80f, 0.80f, 0.80f, 0.56f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); colors[ImGuiCol_CloseButton] = ImVec4(0.59f, 0.59f, 0.59f, 0.50f); colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); } //----------------------------------------------------------------------------- // ImDrawListData //----------------------------------------------------------------------------- ImDrawListSharedData::ImDrawListSharedData() { Font = NULL; FontSize = 0.0f; CurveTessellationTol = 0.0f; ClipRectFullscreen = ImVec4(-8192.0f, -8192.0f, +8192.0f, +8192.0f); // Const data for (int i = 0; i < IM_ARRAYSIZE(CircleVtx12); i++) { const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(CircleVtx12); CircleVtx12[i] = ImVec2(cosf(a), sinf(a)); } } //----------------------------------------------------------------------------- // ImDrawList //----------------------------------------------------------------------------- void ImDrawList::Clear() { CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); Flags = ImDrawListFlags_AntiAliasedLines | ImDrawListFlags_AntiAliasedFill; _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(); } // Using macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug builds #define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : _Data->ClipRectFullscreen) #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 (curr_cmd->ElemCount == 0 && 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(_Data->ClipRectFullscreen.x, _Data->ClipRectFullscreen.y), ImVec2(_Data->ClipRectFullscreen.z, _Data->ClipRectFullscreen.w)); } 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/32 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; } } UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. _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_old_size = VtxBuffer.Size; VtxBuffer.resize(vtx_buffer_old_size + vtx_count); _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size; int idx_buffer_old_size = IdxBuffer.Size; IdxBuffer.resize(idx_buffer_old_size + idx_count); _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_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(_Data->TexUvWhitePixel); 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) { if (points_count < 2) return; const ImVec2 uv = _Data->TexUvWhitePixel; int count = points_count; if (!closed) count = points_count-1; const bool thick_line = thickness > 1.0f; if (Flags & ImDrawListFlags_AntiAliasedLines) { // Anti-aliased stroke const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; 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) { const ImVec2 uv = _Data->TexUvWhitePixel; if (Flags & ImDrawListFlags_AntiAliasedFill) { // Anti-aliased Fill const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; 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 a_min_of_12, int a_max_of_12) { if (radius == 0.0f || a_min_of_12 > a_max_of_12) { _Path.push_back(centre); return; } _Path.reserve(_Path.Size + (a_max_of_12 - a_min_of_12 + 1)); for (int a = a_min_of_12; a <= a_max_of_12; a++) { const ImVec2& c = _Data->CircleVtx12[a % IM_ARRAYSIZE(_Data->CircleVtx12)]; _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius)); } } void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments) { if (radius == 0.0f) { _Path.push_back(centre); return; } _Path.reserve(_Path.Size + (num_segments + 1)); for (int i = 0; i <= num_segments; i++) { const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min); _Path.push_back(ImVec2(centre.x + cosf(a) * radius, centre.y + sinf(a) * radius)); } } static void PathBezierToCasteljau(ImVector* 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, _Data->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) { rounding = ImMin(rounding, fabsf(b.x - a.x) * ( ((rounding_corners & ImDrawCornerFlags_Top) == ImDrawCornerFlags_Top) || ((rounding_corners & ImDrawCornerFlags_Bot) == ImDrawCornerFlags_Bot) ? 0.5f : 1.0f ) - 1.0f); rounding = ImMin(rounding, fabsf(b.y - a.y) * ( ((rounding_corners & ImDrawCornerFlags_Left) == ImDrawCornerFlags_Left) || ((rounding_corners & ImDrawCornerFlags_Right) == ImDrawCornerFlags_Right) ? 0.5f : 1.0f ) - 1.0f); if (rounding <= 0.0f || rounding_corners == 0) { PathLineTo(a); PathLineTo(ImVec2(b.x, a.y)); PathLineTo(b); PathLineTo(ImVec2(a.x, b.y)); } else { const float rounding_tl = (rounding_corners & ImDrawCornerFlags_TopLeft) ? rounding : 0.0f; const float rounding_tr = (rounding_corners & ImDrawCornerFlags_TopRight) ? rounding : 0.0f; const float rounding_br = (rounding_corners & ImDrawCornerFlags_BotRight) ? rounding : 0.0f; const float rounding_bl = (rounding_corners & ImDrawCornerFlags_BotLeft) ? rounding : 0.0f; PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9); PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12); PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3); PathArcToFast(ImVec2(a.x + rounding_bl, b.y - rounding_bl), rounding_bl, 3, 6); } } void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 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_flags, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.5f,0.5f), rounding, rounding_corners_flags); PathStroke(col, true, thickness); } void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags) { if ((col & IM_COL32_A_MASK) == 0) return; if (rounding > 0.0f) { PathRect(a, b, rounding, rounding_corners_flags); PathFillConvex(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) & IM_COL32_A_MASK) == 0) return; const ImVec2 uv = _Data->TexUvWhitePixel; 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 & IM_COL32_A_MASK) == 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 & IM_COL32_A_MASK) == 0) return; PathLineTo(a); PathLineTo(b); PathLineTo(c); PathLineTo(d); PathFillConvex(col); } void ImDrawList::AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 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 & IM_COL32_A_MASK) == 0) return; PathLineTo(a); PathLineTo(b); PathLineTo(c); PathFillConvex(col); } void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments, float thickness) { if ((col & IM_COL32_A_MASK) == 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 & IM_COL32_A_MASK) == 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); PathFillConvex(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 & IM_COL32_A_MASK) == 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 & IM_COL32_A_MASK) == 0) return; if (text_end == NULL) text_end = text_begin + strlen(text_begin); if (text_begin == text_end) return; // Pull default font/size from the shared ImDrawListSharedData instance if (font == NULL) font = _Data->Font; if (font_size == 0.0f) font_size = _Data->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(NULL, 0.0f, pos, col, text_begin, text_end); } void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; 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, uv_a, uv_b, col); if (push_texture_id) PopTextureID(); } void ImDrawList::AddImageQuad(ImTextureID user_texture_id, 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) { if ((col & IM_COL32_A_MASK) == 0) return; const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); if (push_texture_id) PushTextureID(user_texture_id); PrimReserve(6, 4); PrimQuadUV(a, b, c, d, uv_a, uv_b, uv_c, uv_d, col); if (push_texture_id) PopTextureID(); } void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners) { if ((col & IM_COL32_A_MASK) == 0) return; if (rounding <= 0.0f || (rounding_corners & ImDrawCornerFlags_All) == 0) { AddImage(user_texture_id, a, b, uv_a, uv_b, col); return; } const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); if (push_texture_id) PushTextureID(user_texture_id); int vert_start_idx = VtxBuffer.Size; PathRect(a, b, rounding, rounding_corners); PathFillConvex(col); int vert_end_idx = VtxBuffer.Size; ImGui::ShadeVertsLinearUV(VtxBuffer.Data + vert_start_idx, VtxBuffer.Data + vert_end_idx, a, b, uv_a, uv_b, true); 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 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); } } } //----------------------------------------------------------------------------- // Shade functions //----------------------------------------------------------------------------- // Generic linear color gradient, write to RGB fields, leave A untouched. void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawVert* vert_start, ImDrawVert* vert_end, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1) { ImVec2 gradient_extent = gradient_p1 - gradient_p0; float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent); for (ImDrawVert* vert = vert_start; vert < vert_end; vert++) { float d = ImDot(vert->pos - gradient_p0, gradient_extent); float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f); int r = ImLerp((int)(col0 >> IM_COL32_R_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_R_SHIFT) & 0xFF, t); int g = ImLerp((int)(col0 >> IM_COL32_G_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_G_SHIFT) & 0xFF, t); int b = ImLerp((int)(col0 >> IM_COL32_B_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_B_SHIFT) & 0xFF, t); vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK); } } // Scan and shade backward from the end of given vertices. Assume vertices are text only (= vert_start..vert_end going left to right) so we can break as soon as we are out the gradient bounds. void ImGui::ShadeVertsLinearAlphaGradientForLeftToRightText(ImDrawVert* vert_start, ImDrawVert* vert_end, float gradient_p0_x, float gradient_p1_x) { float gradient_extent_x = gradient_p1_x - gradient_p0_x; float gradient_inv_length2 = 1.0f / (gradient_extent_x * gradient_extent_x); int full_alpha_count = 0; for (ImDrawVert* vert = vert_end - 1; vert >= vert_start; vert--) { float d = (vert->pos.x - gradient_p0_x) * (gradient_extent_x); float alpha_mul = 1.0f - ImClamp(d * gradient_inv_length2, 0.0f, 1.0f); if (alpha_mul >= 1.0f && ++full_alpha_count > 2) return; // Early out int a = (int)(((vert->col >> IM_COL32_A_SHIFT) & 0xFF) * alpha_mul); vert->col = (vert->col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); } } // Distribute UV over (a, b) rectangle void ImGui::ShadeVertsLinearUV(ImDrawVert* vert_start, ImDrawVert* vert_end, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp) { const ImVec2 size = b - a; const ImVec2 uv_size = uv_b - uv_a; const ImVec2 scale = ImVec2( size.x != 0.0f ? (uv_size.x / size.x) : 0.0f, size.y != 0.0f ? (uv_size.y / size.y) : 0.0f); if (clamp) { const ImVec2 min = ImMin(uv_a, uv_b); const ImVec2 max = ImMax(uv_a, uv_b); for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex) vertex->uv = ImClamp(uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale), min, max); } else { for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex) vertex->uv = uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale); } } //----------------------------------------------------------------------------- // ImFontConfig //----------------------------------------------------------------------------- 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); GlyphOffset = ImVec2(0.0f, 0.0f); GlyphRanges = NULL; MergeMode = false; RasterizerFlags = 0x00; RasterizerMultiply = 1.0f; memset(Name, 0, sizeof(Name)); DstFont = NULL; } //----------------------------------------------------------------------------- // ImFontAtlas //----------------------------------------------------------------------------- // 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 FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF = 90; const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27; const unsigned int FONT_ATLAS_DEFAULT_TEX_DATA_ID = 0x80000000; static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * FONT_ATLAS_DEFAULT_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 - " }; static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[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_ResizeAll { 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 }; ImFontAtlas::ImFontAtlas() { Flags = 0x00; TexID = NULL; TexDesiredWidth = 0; TexGlyphPadding = 1; TexPixelsAlpha8 = NULL; TexPixelsRGBA32 = NULL; TexWidth = TexHeight = 0; TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++) CustomRectIds[n] = -1; } 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(); CustomRects.clear(); for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++) CustomRectIds[n] = -1; } 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++) IM_DELETE(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 = NULL; GetTexDataAsAlpha8(&pixels, NULL, NULL); if (pixels) { 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) Fonts.push_back(IM_NEW(ImFont)); else IM_ASSERT(!Fonts.empty()); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui 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 misc/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-endianness. 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, "ProggyClean.ttf, 13px"); if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f; const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &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 = ImFileLoadToMemory(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, %.0fpx", p, size_pixels); } return AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg, glyph_ranges); } // NB: 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; } int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height) { IM_ASSERT(id >= 0x10000); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); CustomRect r; r.ID = id; r.Width = (unsigned short)width; r.Height = (unsigned short)height; CustomRects.push_back(r); return CustomRects.Size - 1; // Return index } int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset) { IM_ASSERT(font != NULL); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); CustomRect r; r.ID = id; r.Width = (unsigned short)width; r.Height = (unsigned short)height; r.GlyphAdvanceX = advance_x; r.GlyphOffset = offset; r.Font = font; CustomRects.push_back(r); return CustomRects.Size - 1; // Return index } void ImFontAtlas::CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) { IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y); *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y); } bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) { if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_Count_) return false; if (Flags & ImFontAtlasFlags_NoMouseCursors) return false; ImFontAtlas::CustomRect& r = CustomRects[CustomRectIds[0]]; IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r.X, (float)r.Y); ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; *out_size = size; *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; out_uv_border[0] = (pos) * TexUvScale; out_uv_border[1] = (pos + size) * TexUvScale; pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; out_uv_fill[0] = (pos) * TexUvScale; out_uv_fill[1] = (pos + size) * TexUvScale; return true; } bool ImFontAtlas::Build() { return ImFontAtlasBuildWithStbTruetype(this); } void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor) { for (unsigned int i = 0; i < 256; i++) { unsigned int value = (unsigned int)(i * in_brighten_factor); out_table[i] = value > 255 ? 255 : (value & 0xFF); } } void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride) { unsigned char* data = pixels + x + y * stride; for (int j = h; j > 0; j--, data += stride) for (int i = 0; i < w; i++) data[i] = table[data[i]]; } bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) { IM_ASSERT(atlas->ConfigData.Size > 0); ImFontAtlasBuildRegisterDefaultCustomRects(atlas); atlas->TexID = NULL; atlas->TexWidth = atlas->TexHeight = 0; atlas->TexUvScale = ImVec2(0.0f, 0.0f); atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f); atlas->ClearTexData(); // Count glyphs/ranges int total_glyphs_count = 0; int total_ranges_count = 0; for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) { ImFontConfig& cfg = atlas->ConfigData[input_i]; if (!cfg.GlyphRanges) cfg.GlyphRanges = atlas->GetGlyphRangesDefault(); for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2, total_ranges_count++) total_glyphs_count += (in_range[1] - in_range[0]) + 1; } // We need a width for the skyline algorithm. Using a dumb heuristic here to decide of width. User can override TexDesiredWidth and TexGlyphPadding if they wish. // Width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height. atlas->TexWidth = (atlas->TexDesiredWidth > 0) ? atlas->TexDesiredWidth : (total_glyphs_count > 4000) ? 4096 : (total_glyphs_count > 2000) ? 2048 : (total_glyphs_count > 1000) ? 1024 : 512; atlas->TexHeight = 0; // Start packing const int max_tex_height = 1024*32; stbtt_pack_context spc = {}; if (!stbtt_PackBegin(&spc, NULL, atlas->TexWidth, max_tex_height, 0, atlas->TexGlyphPadding, NULL)) return false; 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). ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info); // Initialize font information (so we can error without any cleanup) struct ImFontTempBuildData { stbtt_fontinfo FontInfo; stbrp_rect* Rects; int RectsCount; stbtt_pack_range* Ranges; int RangesCount; }; ImFontTempBuildData* tmp_array = (ImFontTempBuildData*)ImGui::MemAlloc((size_t)atlas->ConfigData.Size * sizeof(ImFontTempBuildData)); for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) { ImFontConfig& cfg = atlas->ConfigData[input_i]; ImFontTempBuildData& tmp = tmp_array[input_i]; IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas)); 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)) { atlas->TexWidth = atlas->TexHeight = 0; // Reset output on failure ImGui::MemFree(tmp_array); return false; } } // 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_glyphs_count * sizeof(stbtt_packedchar)); stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyphs_count * sizeof(stbrp_rect)); stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_ranges_count * sizeof(stbtt_pack_range)); memset(buf_packedchars, 0, total_glyphs_count * sizeof(stbtt_packedchar)); memset(buf_rects, 0, total_glyphs_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity. memset(buf_ranges, 0, total_ranges_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 < atlas->ConfigData.Size; input_i++) { ImFontConfig& cfg = atlas->ConfigData[input_i]; ImFontTempBuildData& tmp = tmp_array[input_i]; // Setup ranges int font_glyphs_count = 0; int font_ranges_count = 0; for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2, font_ranges_count++) font_glyphs_count += (in_range[1] - in_range[0]) + 1; tmp.Ranges = buf_ranges + buf_ranges_n; tmp.RangesCount = font_ranges_count; buf_ranges_n += font_ranges_count; for (int i = 0; i < font_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; tmp.RectsCount = font_glyphs_count; buf_rects_n += font_glyphs_count; stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); int n = stbtt_PackFontRangesGatherRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); IM_ASSERT(n == font_glyphs_count); 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) atlas->TexHeight = ImMax(atlas->TexHeight, tmp.Rects[i].y + tmp.Rects[i].h); } IM_ASSERT(buf_rects_n == total_glyphs_count); IM_ASSERT(buf_packedchars_n == total_glyphs_count); IM_ASSERT(buf_ranges_n == total_ranges_count); // Create texture atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); atlas->TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(atlas->TexWidth * atlas->TexHeight); memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight); spc.pixels = atlas->TexPixelsAlpha8; spc.height = atlas->TexHeight; // Second pass: render font characters for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) { ImFontConfig& cfg = atlas->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); if (cfg.RasterizerMultiply != 1.0f) { unsigned char multiply_table[256]; ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply); for (const stbrp_rect* r = tmp.Rects; r != tmp.Rects + tmp.RectsCount; r++) if (r->was_packed) ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, spc.pixels, r->x, r->y, r->w, r->h, spc.stride_in_bytes); } 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 < atlas->ConfigData.Size; input_i++) { ImFontConfig& cfg = atlas->ConfigData[input_i]; ImFontTempBuildData& tmp = tmp_array[input_i]; ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true) const 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); const float ascent = unscaled_ascent * font_scale; const float descent = unscaled_descent * font_scale; ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent); const float off_x = cfg.GlyphOffset.x; const float off_y = cfg.GlyphOffset.y + (float)(int)(dst_font->Ascent + 0.5f); 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, atlas->TexWidth, atlas->TexHeight, char_idx, &dummy_x, &dummy_y, &q, 0); dst_font->AddGlyph((ImWchar)codepoint, q.x0 + off_x, q.y0 + off_y, q.x1 + off_x, q.y1 + off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance); } } } // Cleanup temporaries ImGui::MemFree(buf_packedchars); ImGui::MemFree(buf_ranges); ImGui::MemFree(tmp_array); ImFontAtlasBuildFinish(atlas); return true; } void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas) { if (atlas->CustomRectIds[0] >= 0) return; if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1, FONT_ATLAS_DEFAULT_TEX_DATA_H); else atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, 2, 2); } void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent) { if (!font_config->MergeMode) { font->ClearOutputData(); font->FontSize = font_config->SizePixels; font->ConfigData = font_config; font->ContainerAtlas = atlas; font->Ascent = ascent; font->Descent = descent; } font->ConfigDataCount++; } void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* pack_context_opaque) { stbrp_context* pack_context = (stbrp_context*)pack_context_opaque; ImVector& user_rects = atlas->CustomRects; IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong. ImVector pack_rects; pack_rects.resize(user_rects.Size); memset(pack_rects.Data, 0, sizeof(stbrp_rect) * user_rects.Size); for (int i = 0; i < user_rects.Size; i++) { pack_rects[i].w = user_rects[i].Width; pack_rects[i].h = user_rects[i].Height; } stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size); for (int i = 0; i < pack_rects.Size; i++) if (pack_rects[i].was_packed) { user_rects[i].X = pack_rects[i].x; user_rects[i].Y = pack_rects[i].y; IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height); atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h); } } static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) { IM_ASSERT(atlas->CustomRectIds[0] >= 0); IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlas::CustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]]; IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); IM_ASSERT(r.IsPacked()); const int w = atlas->TexWidth; if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) { // Render/copy pixels IM_ASSERT(r.Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r.Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); for (int y = 0, n = 0; y < FONT_ATLAS_DEFAULT_TEX_DATA_H; y++) for (int x = 0; x < FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF; x++, n++) { const int offset0 = (int)(r.X + x) + (int)(r.Y + y) * w; const int offset1 = offset0 + FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; atlas->TexPixelsAlpha8[offset0] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == '.' ? 0xFF : 0x00; atlas->TexPixelsAlpha8[offset1] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == 'X' ? 0xFF : 0x00; } } else { IM_ASSERT(r.Width == 2 && r.Height == 2); const int offset = (int)(r.X) + (int)(r.Y) * w; atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF; } atlas->TexUvWhitePixel = ImVec2((r.X + 0.5f) * atlas->TexUvScale.x, (r.Y + 0.5f) * atlas->TexUvScale.y); } void ImFontAtlasBuildFinish(ImFontAtlas* atlas) { // Render into our custom data block ImFontAtlasBuildRenderDefaultTexData(atlas); // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) { const ImFontAtlas::CustomRect& r = atlas->CustomRects[i]; if (r.Font == NULL || r.ID > 0x10000) continue; IM_ASSERT(r.Font->ContainerAtlas == atlas); ImVec2 uv0, uv1; atlas->CalcCustomRectUV(&r, &uv0, &uv1); r.Font->AddGlyph((ImWchar)r.ID, r.GlyphOffset.x, r.GlyphOffset.y, r.GlyphOffset.x + r.Width, r.GlyphOffset.y + r.Height, uv0.x, uv0.y, uv1.x, uv1.y, r.GlyphAdvanceX); } // Build all fonts lookup tables for (int i = 0; i < atlas->Fonts.Size; i++) atlas->Fonts[i]->BuildLookupTable(); } // 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 is designed to helps us reduce the source code size. // FIXME: Source a list of the revised 2136 joyo kanji list from 2010 and rebuild this. // The current list was sourced from http://theinstructionlimit.com/author/renaudbedardrenaudbedard/page/3 // Note that you may use ImFontAtlas::GlyphRangesBuilder to create your own ranges, by merging existing ranges or adding new characters. 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 0x2010, 0x205E, // Punctuations 0x0E00, 0x0E7F, // Thai 0, }; return &ranges[0]; } //----------------------------------------------------------------------------- // ImFontAtlas::GlyphRangesBuilder //----------------------------------------------------------------------------- void ImFontAtlas::GlyphRangesBuilder::AddText(const char* text, const char* text_end) { while (text_end ? (text < text_end) : *text) { unsigned int c = 0; int c_len = ImTextCharFromUtf8(&c, text, text_end); text += c_len; if (c_len == 0) break; if (c < 0x10000) AddChar((ImWchar)c); } } void ImFontAtlas::GlyphRangesBuilder::AddRanges(const ImWchar* ranges) { for (; ranges[0]; ranges += 2) for (ImWchar c = ranges[0]; c <= ranges[1]; c++) AddChar(c); } void ImFontAtlas::GlyphRangesBuilder::BuildRanges(ImVector* out_ranges) { for (int n = 0; n < 0x10000; n++) if (GetBit(n)) { out_ranges->push_back((ImWchar)n); while (n < 0x10000 && GetBit(n + 1)) n++; out_ranges->push_back((ImWchar)n); } out_ranges->push_back(0); } //----------------------------------------------------------------------------- // ImFont //----------------------------------------------------------------------------- ImFont::ImFont() { Scale = 1.0f; FallbackChar = (ImWchar)'?'; DisplayOffset = ImVec2(0.0f, 1.0f); ClearOutputData(); } 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; */ ClearOutputData(); } void ImFont::ClearOutputData() { FontSize = 0.0f; Glyphs.clear(); IndexAdvanceX.clear(); IndexLookup.clear(); FallbackGlyph = NULL; FallbackAdvanceX = 0.0f; ConfigDataCount = 0; ConfigData = NULL; ContainerAtlas = NULL; Ascent = Descent = 0.0f; MetricsTotalSurface = 0; } 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 IndexAdvanceX.clear(); IndexLookup.clear(); GrowIndex(max_codepoint + 1); for (int i = 0; i < Glyphs.Size; i++) { int codepoint = (int)Glyphs[i].Codepoint; IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX; 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); ImFontGlyph& tab_glyph = Glyphs.back(); tab_glyph = *FindGlyph((unsigned short)' '); tab_glyph.Codepoint = '\t'; tab_glyph.AdvanceX *= 4; IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX; IndexLookup[(int)tab_glyph.Codepoint] = (unsigned short)(Glyphs.Size-1); } FallbackGlyph = NULL; FallbackGlyph = FindGlyph(FallbackChar); FallbackAdvanceX = FallbackGlyph ? FallbackGlyph->AdvanceX : 0.0f; for (int i = 0; i < max_codepoint + 1; i++) if (IndexAdvanceX[i] < 0.0f) IndexAdvanceX[i] = FallbackAdvanceX; } void ImFont::SetFallbackChar(ImWchar c) { FallbackChar = c; BuildLookupTable(); } void ImFont::GrowIndex(int new_size) { IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); if (new_size <= IndexLookup.Size) return; IndexAdvanceX.resize(new_size, -1.0f); IndexLookup.resize(new_size, (unsigned short)-1); } void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) { Glyphs.resize(Glyphs.Size + 1); ImFontGlyph& glyph = Glyphs.back(); glyph.Codepoint = (ImWchar)codepoint; glyph.X0 = x0; glyph.Y0 = y0; glyph.X1 = x1; glyph.Y1 = y1; glyph.U0 = u0; glyph.V0 = v0; glyph.U1 = u1; glyph.V1 = v1; glyph.AdvanceX = advance_x + ConfigData->GlyphExtraSpacing.x; // Bake spacing into AdvanceX if (ConfigData->PixelSnapH) glyph.AdvanceX = (float)(int)(glyph.AdvanceX + 0.5f); // Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round) MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + 1.99f) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + 1.99f); } 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; IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f; } const ImFontGlyph* ImFont::FindGlyph(ImWchar 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; wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters 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 < IndexAdvanceX.Size ? IndexAdvanceX[(int)c] : FallbackAdvanceX); if (ImCharIsSpace(c)) { if (inside_word) { line_width += blank_width; blank_width = 0.0f; word_end = s; } 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) // Malformed UTF-8? 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 < IndexAdvanceX.Size ? IndexAdvanceX[(int)c] : FallbackAdvanceX) * 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 ImFontGlyph* 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; draw_list->PrimReserve(6, 4); draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale), ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale), 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); // ImGui functions generally already provides a valid text_end, so this is merely to handle direct calls. // 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) // Malformed UTF-8? 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 ImFontGlyph* glyph = FindGlyph((unsigned short)c)) { char_width = glyph->AdvanceX * 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 builds. 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; } //----------------------------------------------------------------------------- // Internals Drawing Helpers //----------------------------------------------------------------------------- static inline float ImAcos01(float x) { if (x <= 0.0f) return IM_PI * 0.5f; if (x >= 1.0f) return 0.0f; return acosf(x); //return (-0.69813170079773212f * x * x - 0.87266462599716477f) * x + 1.5707963267948966f; // Cheap approximation, may be enough for what we do. } // FIXME: Cleanup and move code to ImDrawList. void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding) { if (x_end_norm == x_start_norm) return; if (x_start_norm > x_end_norm) ImSwap(x_start_norm, x_end_norm); ImVec2 p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y); ImVec2 p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y); if (rounding == 0.0f) { draw_list->AddRectFilled(p0, p1, col, 0.0f); return; } rounding = ImClamp(ImMin((rect.Max.x - rect.Min.x) * 0.5f, (rect.Max.y - rect.Min.y) * 0.5f) - 1.0f, 0.0f, rounding); const float inv_rounding = 1.0f / rounding; const float arc0_b = ImAcos01(1.0f - (p0.x - rect.Min.x) * inv_rounding); const float arc0_e = ImAcos01(1.0f - (p1.x - rect.Min.x) * inv_rounding); const float x0 = ImMax(p0.x, rect.Min.x + rounding); if (arc0_b == arc0_e) { draw_list->PathLineTo(ImVec2(x0, p1.y)); draw_list->PathLineTo(ImVec2(x0, p0.y)); } else if (arc0_b == 0.0f && arc0_e == IM_PI*0.5f) { draw_list->PathArcToFast(ImVec2(x0, p1.y - rounding), rounding, 3, 6); // BL draw_list->PathArcToFast(ImVec2(x0, p0.y + rounding), rounding, 6, 9); // TR } else { draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b, 3); // BL draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e, 3); // TR } if (p1.x > rect.Min.x + rounding) { const float arc1_b = ImAcos01(1.0f - (rect.Max.x - p1.x) * inv_rounding); const float arc1_e = ImAcos01(1.0f - (rect.Max.x - p0.x) * inv_rounding); const float x1 = ImMin(p1.x, rect.Max.x - rounding); if (arc1_b == arc1_e) { draw_list->PathLineTo(ImVec2(x1, p0.y)); draw_list->PathLineTo(ImVec2(x1, p1.y)); } else if (arc1_b == 0.0f && arc1_e == IM_PI*0.5f) { draw_list->PathArcToFast(ImVec2(x1, p0.y + rounding), rounding, 9, 12); // TR draw_list->PathArcToFast(ImVec2(x1, p1.y - rounding), rounding, 0, 3); // BR } else { draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b, 3); // TR draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e, 3); // BR } } draw_list->PathFillConvex(col); } //----------------------------------------------------------------------------- // DEFAULT FONT DATA //----------------------------------------------------------------------------- // Compressed with stb_compress() then converted to a C array. // Use the program in misc/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^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;--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&VZ>1i%h1S9u5o@YaaW$e+bROPOpxTO7Stwi1::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[iLAw=4h(9.`G" "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?Ggv:[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+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[Ket`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-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'$MhLbxfc$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$'?;++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&VBpqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<-+k?'(^](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#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-m2KgLQ_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@aege0jT6'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`.d*(B`-n8D9oK-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P r+$%CE=68>K8r0=dSC%%(@p7" ".m7jilQ02'0-VWAgTlGW'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#%8cY#YZ?=,`Wdxu/ae&#" "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$so8lKN%5/$(vdfq7+ebA#" "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(%:_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#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^xBdLjLV#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#SfD07&6D@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5" "_>@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'wYmTFmLq9wI>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$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,?1839FWdFTi1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IXSsDiWP,##P`%/L-" "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdFl*: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&#$(>.Z-I&J(Q0Hd5Q%7Co-b`-cP)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8WlA2);Sa" ">gXm8YB`1d@K#n]76-a$U,mF%Ul:#/'xoFM9QX-$.QN'>" "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B2Qft^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'1h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-uW%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*'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" "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#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#?,)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; } ================================================ FILE: ui/imgui/imgui_impl_glfw_gl3.cpp ================================================ // ImGui GLFW binding with OpenGL3 + shaders // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) // (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.) // Implemented features: // [X] User texture binding. Cast 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. // [X] Gamepad navigation mapping. Enable with 'io.NavFlags |= ImGuiNavFlags_EnableGamepad'. // 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 // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplGlfwGL3_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. // 2018-01-25: Inputs: Added gamepad support if ImGuiNavFlags_EnableGamepad is set. // 2018-01-25: Inputs: Honoring the io.WantMoveMouse by repositioning the mouse by using navigation and ImGuiNavFlags_MoveMouse is set. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert. // 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150. (Also changed GL context from 3.3 to 3.2 in example's main.cpp) // 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode. // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1). // 2017-05-01: OpenGL: Fixed save and restore of current blend function state. // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle. // 2016-04-30: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE. #include "imgui.h" #include "imgui_impl_glfw_gl3.h" #include "imgui_internal.h" // GL3W/GLFW #include #include #include #include // Data static GLFWwindow* g_Window = NULL; static double g_Time = 0.0f; static bool g_MouseJustPressed[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; static void (*g_Callback)(void *data); static void* g_CallbackData; static bool g_Scheduled = false; static uv_timer_t g_UvRedrawTimer; static uv_poll_t g_UvPoll; // OpenGL3 Render function. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. void ImGui_ImplGlfwGL3_RenderDrawData(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 GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture); glActiveTexture(GL_TEXTURE0); GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); GLint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, &last_sampler); 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_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb); GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb); GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha); GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha); GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb); GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha); 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, polygon fill 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); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // 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); glBindSampler(0, 0); // Rely on combined texture/sampler state. 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), (const 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), (const 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); glBindTexture(GL_TEXTURE_2D, last_texture); glBindSampler(0, last_sampler); glActiveTexture(last_active_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); glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); 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); glPolygonMode(GL_FRONT_AND_BACK, last_polygon_mode[0]); 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(void* user_data) { return glfwGetClipboardString((GLFWwindow*)user_data); } static void ImGui_ImplGlfwGL3_SetClipboardText(void* user_data, const char* text) { glfwSetClipboardString((GLFWwindow*)user_data, text); } void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/) { if (action == GLFW_PRESS && button >= 0 && button < 3) g_MouseJustPressed[button] = true; } void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow*, double xoffset, double yoffset) { ImGuiIO& io = ImGui::GetIO(); io.MouseWheelH += (float)xoffset; io.MouseWheel += (float)yoffset; } 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); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); 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 150\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 150\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); glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col)); 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; } } static void Libuv_Poll_Callback(uv_poll_t* handle, int status, int events) { glfwPollEvents(); g_Callback(g_CallbackData); } static void Libuv_Redraw_Callback(uv_timer_t* handle) { g_Scheduled = false; glfwPollEvents(); g_Callback(g_CallbackData); } bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, void (*callback)(void *), void *data) { g_Window = window; g_Callback = callback; g_CallbackData = data; 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_Insert] = GLFW_KEY_INSERT; io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE; 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.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText; io.ClipboardUserData = g_Window; #ifdef _WIN32 io.ImeWindowHandle = glfwGetWin32Window(g_Window); #endif glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL3_MouseButtonCallback); glfwSetScrollCallback(window, ImGui_ImplGlfwGL3_ScrollCallback); glfwSetKeyCallback(window, ImGui_ImplGlfwGL3_KeyCallback); glfwSetCharCallback(window, ImGui_ImplGlfwGL3_CharCallback); int native_fd = -1; #ifdef GLFW_EXPOSE_NATIVE_X11 if (glfwGetX11Display()) native_fd = XConnectionNumber(glfwGetX11Display()); #elif GLFW_EXPOSE_NATIVE_WAYLAND if (glfwGetWaylandDisplay()) native_fd = wl_display_get_fd(glfwGetWaylandDisplay()); #endif if (native_fd < 0) return false; if (uv_timer_init(uv_default_loop(), &g_UvRedrawTimer)) return false; if (uv_timer_start(&g_UvRedrawTimer, Libuv_Redraw_Callback, 16, false)) return false; if (uv_poll_init(uv_default_loop(), &g_UvPoll, native_fd)) return false; if (uv_poll_start(&g_UvPoll, UV_READABLE | UV_DISCONNECT, Libuv_Poll_Callback)) return false; return true; } void ImGui_ImplGlfwGL3_Shutdown() { ImGui_ImplGlfwGL3_InvalidateDeviceObjects(); } 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)) { if (io.WantMoveMouse) { glfwSetCursorPos(g_Window, (double)io.MousePos.x, (double)io.MousePos.y); // Set mouse position if requested by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation) } else { double mouse_x, mouse_y; glfwGetCursorPos(g_Window, &mouse_x, &mouse_y); io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); } } else { io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX); } for (int i = 0; i < 3; i++) { // 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. io.MouseDown[i] = g_MouseJustPressed[i] || glfwGetMouseButton(g_Window, i) != 0; g_MouseJustPressed[i] = false; } // Hide OS mouse cursor if ImGui is drawing it glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL); // Gamepad navigation mapping [BETA] memset(io.NavInputs, 0, sizeof(io.NavInputs)); if (io.NavFlags & ImGuiNavFlags_EnableGamepad) { // Update gamepad inputs #define MAP_BUTTON(NAV_NO, BUTTON_NO) { if (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS) io.NavInputs[NAV_NO] = 1.0f; } #define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); if (v > 1.0f) v = 1.0f; if (io.NavInputs[NAV_NO] < v) io.NavInputs[NAV_NO] = v; } int axes_count = 0, buttons_count = 0; const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count); const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count); MAP_BUTTON(ImGuiNavInput_Activate, 0); // Cross / A MAP_BUTTON(ImGuiNavInput_Cancel, 1); // Circle / B MAP_BUTTON(ImGuiNavInput_Menu, 2); // Square / X MAP_BUTTON(ImGuiNavInput_Input, 3); // Triangle / Y MAP_BUTTON(ImGuiNavInput_DpadLeft, 13); // D-Pad Left MAP_BUTTON(ImGuiNavInput_DpadRight, 11); // D-Pad Right MAP_BUTTON(ImGuiNavInput_DpadUp, 10); // D-Pad Up MAP_BUTTON(ImGuiNavInput_DpadDown, 12); // D-Pad Down MAP_BUTTON(ImGuiNavInput_FocusPrev, 4); // L1 / LB MAP_BUTTON(ImGuiNavInput_FocusNext, 5); // R1 / RB MAP_BUTTON(ImGuiNavInput_TweakSlow, 4); // L1 / LB MAP_BUTTON(ImGuiNavInput_TweakFast, 5); // R1 / RB MAP_ANALOG(ImGuiNavInput_LStickLeft, 0, -0.3f, -0.9f); MAP_ANALOG(ImGuiNavInput_LStickRight,0, +0.3f, +0.9f); MAP_ANALOG(ImGuiNavInput_LStickUp, 1, +0.3f, +0.9f); MAP_ANALOG(ImGuiNavInput_LStickDown, 1, -0.3f, -0.9f); #undef MAP_BUTTON #undef MAP_ANALOG } // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application. ImGui::NewFrame(); } void ImGui_ImplGlfwGL3_ScheduleFrame() { if (g_Scheduled) return; g_Scheduled = true; uv_timer_again(&g_UvRedrawTimer); } ================================================ FILE: ui/imgui/imgui_impl_glfw_gl3.h ================================================ // ImGui GLFW binding with OpenGL3 + shaders // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) // (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.) // Implemented features: // [X] User texture binding. Cast 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. // [X] Gamepad navigation mapping. Enable with 'io.NavFlags |= ImGuiNavFlags_EnableGamepad'. // 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, void (*callback)(void *), void *data); IMGUI_API void ImGui_ImplGlfwGL3_Shutdown(); IMGUI_API void ImGui_ImplGlfwGL3_NewFrame(); IMGUI_API void ImGui_ImplGlfwGL3_RenderDrawData(ImDrawData* draw_data); // 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); IMGUI_API void ImGui_ImplGlfwGL3_ScheduleFrame(); ================================================ FILE: ui/imgui/imgui_impl_gtk3_cogl.cpp ================================================ // 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 #include #include "imgui_impl_gtk3_cogl.h" #if defined(GDK_WINDOWING_WAYLAND) #include #endif #if defined(GDK_WINDOWING_X11) #include #endif #if defined(GDK_WINDOWING_WIN32) #include #endif #if defined(COGL_HAS_EGL_PLATFORM_WAYLAND_SUPPORT) #include #endif #if defined(COGL_HAS_XLIB_SUPPORT) #include #endif #define ARRAY_SIZE(arg) (sizeof(arg) / sizeof((arg)[0])) #define EVENT_MASK \ ((GdkEventMask) \ (GDK_STRUCTURE_MASK | \ GDK_FOCUS_CHANGE_MASK | \ GDK_EXPOSURE_MASK | \ GDK_PROPERTY_CHANGE_MASK | \ GDK_ENTER_NOTIFY_MASK | \ GDK_LEAVE_NOTIFY_MASK | \ GDK_KEY_PRESS_MASK | \ GDK_KEY_RELEASE_MASK | \ GDK_BUTTON_PRESS_MASK | \ GDK_BUTTON_RELEASE_MASK | \ GDK_POINTER_MOTION_MASK | \ GDK_SMOOTH_SCROLL_MASK | \ GDK_SCROLL_MASK)) // Data static GtkWidget* g_GtkWidget = NULL; static GdkWindow* g_GdkWindow = NULL; static CoglContext* g_Context = NULL; static CoglFramebuffer* g_Framebuffer = NULL; static guint64 g_Time = 0; static bool g_MousePressed[5] = { false, false, false, false, false }; static ImVec2 g_MousePosition = ImVec2(-1, -1); static float g_MouseWheel = 0.0f; static CoglPipeline* g_ColorPipeline = NULL; static CoglPipeline* g_ImagePipeline = NULL; static int g_NumRedraws = 0; static const struct backend_callbacks* g_Callbacks; static void (*g_Callback)(CoglOnscreen *onscreen, void *data); static void* g_CallbackData; static guint g_RedrawTimeout = 0; // Some Gdk backend specific stuff. struct backend_callbacks { CoglWinsysID winsys; void (*init) (CoglRenderer *renderer, GdkDisplay *display, GdkWindow *window); ImVec2 (*get_scale) (GdkWindow *window); void (*set_window) (CoglOnscreen* onscreen, GdkWindow *window); void (*resize) (GdkWindow *window, CoglOnscreen* onscreen, int width, int height, int x, int y); }; static cairo_region_t *get_window_region(GdkWindow *window) { cairo_rectangle_int_t rect; memset(&rect, 0, sizeof(rect)); gdk_window_get_geometry(window, NULL, NULL, &rect.width, &rect.height); return cairo_region_create_rectangle (&rect); } #if defined(GDK_WINDOWING_WAYLAND) && defined(COGL_HAS_EGL_PLATFORM_WAYLAND_SUPPORT) static void wayland_init(CoglRenderer *renderer, GdkDisplay *display, GdkWindow *window) { cogl_wayland_renderer_set_foreign_display(renderer, gdk_wayland_display_get_wl_display(display)); cogl_wayland_renderer_set_event_dispatch_enabled(renderer, FALSE); } static void wayland_set_window(CoglOnscreen* onscreen, GdkWindow *window) { cogl_wayland_onscreen_set_foreign_surface(onscreen, gdk_wayland_window_get_wl_surface(GDK_WAYLAND_WINDOW(window))); } static void wayland_resize(GdkWindow *window, CoglOnscreen* onscreen, int width, int height, int x, int y) { cogl_wayland_onscreen_resize(onscreen, width, height, 0, 0); } #endif #if defined(GDK_WINDOWING_X11) && defined(COGL_HAS_XLIB_SUPPORT) static void x11_init(CoglRenderer *renderer, GdkDisplay *display, GdkWindow *window) { cogl_xlib_renderer_set_foreign_display(renderer, gdk_x11_display_get_xdisplay(display)); } static ImVec2 x11_get_scale(GdkWindow *window) { int scale = gdk_window_get_scale_factor(window); return ImVec2(scale, scale); } static void x11_window_update_foreign_event_mask(CoglOnscreen *onscreen, guint32 event_mask, void *user_data) { GdkWindow *window = GDK_WINDOW(user_data); /* we assume that a GDK event mask is bitwise compatible with X11 event masks */ gdk_window_set_events(window, (GdkEventMask) (event_mask | EVENT_MASK)); } static GdkFilterReturn cogl_gdk_filter (GdkXEvent *xevent, GdkEvent *event, gpointer data) { CoglRenderer *renderer = cogl_context_get_renderer(g_Context); CoglFilterReturn ret; ret = cogl_xlib_renderer_handle_event (renderer, (XEvent *) xevent); switch (ret) { case COGL_FILTER_REMOVE: return GDK_FILTER_REMOVE; case COGL_FILTER_CONTINUE: default: return GDK_FILTER_CONTINUE; } return GDK_FILTER_CONTINUE; } static void x11_set_window(CoglOnscreen* onscreen, GdkWindow *window) { cogl_x11_onscreen_set_foreign_window_xid(onscreen, GDK_WINDOW_XID(window), x11_window_update_foreign_event_mask, window); gdk_window_add_filter(window, cogl_gdk_filter, onscreen); } static void x11_resize(GdkWindow *window, CoglOnscreen* onscreen, int width, int height, int x, int y) { int scale = gdk_window_get_scale_factor(window); XConfigureEvent xevent; memset(&xevent, 0, sizeof(xevent)); xevent.type = ConfigureNotify; xevent.window = GDK_WINDOW_XID (window); xevent.width = width * scale; xevent.height = height * scale; /* Ensure cogl knows about the new size immediately, as we will * draw before we get the ConfigureNotify response. */ cogl_xlib_renderer_handle_event(cogl_context_get_renderer(g_Context), (XEvent *)&xevent); } #endif #if defined(GDK_WINDOWING_WIN32) && defined(COGL_HAS_WIN32_SUPPORT) static void win32_set_window(CoglOnscreen* onscreen, GdkWindow *window) { cogl_win32_onscreen_set_foreign_window(onscreen, gdk_win32_window_get_handle(window)); } #endif static void noop_init(CoglRenderer *renderer, GdkDisplay *display, GdkWindow *window) { /* NOOP */ } static ImVec2 noop_get_scale(GdkWindow *window) { return ImVec2(1, 1); } static void noop_set_window(CoglOnscreen* onscreen, GdkWindow *window) { /* NOOP */ } static void noop_resize(GdkWindow *window, CoglOnscreen* onscreen, int width, int height, int x, int y) { /* NOOP */ } static const struct backend_callbacks * get_backend_callbacks(GdkWindow *window) { #if defined(GDK_WINDOWING_WAYLAND) && defined(COGL_HAS_EGL_PLATFORM_WAYLAND_SUPPORT) if (GDK_IS_WAYLAND_WINDOW(window)) { static const struct backend_callbacks cbs = { COGL_WINSYS_ID_EGL_WAYLAND, wayland_init, noop_get_scale, wayland_set_window, wayland_resize, }; return &cbs; } #endif #if defined(GDK_WINDOWING_X11) && defined(COGL_HAS_XLIB_SUPPORT) if (GDK_IS_X11_WINDOW(window)) { static const struct backend_callbacks cbs = { //COGL_WINSYS_ID_EGL_XLIB, COGL_WINSYS_ID_GLX, x11_init, x11_get_scale, x11_set_window, x11_resize, }; return &cbs; } #endif #if defined(GDK_WINDOWING_WIN32) && defined(COGL_HAS_WIN32_SUPPORT) if (GDK_IS_WIN32_WINDOW(window)) { static const struct backend_callbacks cbs = { COGL_WINSYS_ID_WGL, noop_init, noop_get_scale, win32_set_window, noop_resize, }; return &cbs; } #endif static const struct backend_callbacks cbs = { COGL_WINSYS_ID_STUB, noop_init, noop_get_scale, noop_set_window, noop_resize, }; return &cbs; } // 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_ImplGtk3Cogl_RenderDrawData(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); cogl_framebuffer_orthographic(g_Framebuffer, 0, 0, io.DisplaySize.x, io.DisplaySize.y, -1, 1); CoglContext *context = cogl_framebuffer_get_context(g_Framebuffer); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; int idx_buffer_offset = 0; CoglAttributeBuffer *vertices = cogl_attribute_buffer_new(context, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), cmd_list->VtxBuffer.Data); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) CoglAttribute *attrs[3] = { cogl_attribute_new(vertices, "cogl_position_in", sizeof(ImDrawVert), OFFSETOF(ImDrawVert, pos), 2, COGL_ATTRIBUTE_TYPE_FLOAT), cogl_attribute_new(vertices, "cogl_tex_coord0_in", sizeof(ImDrawVert), OFFSETOF(ImDrawVert, uv), 2, COGL_ATTRIBUTE_TYPE_FLOAT), cogl_attribute_new(vertices, "cogl_color_in", sizeof(ImDrawVert), OFFSETOF(ImDrawVert, col), 4, COGL_ATTRIBUTE_TYPE_UNSIGNED_BYTE) }; #undef OFFSETOF CoglPrimitive *primitive = cogl_primitive_new_with_attributes(COGL_VERTICES_MODE_TRIANGLES, cmd_list->VtxBuffer.Size, attrs, 3); CoglIndices *indices = cogl_indices_new(context, sizeof(ImDrawIdx) == 2 ? COGL_INDICES_TYPE_UNSIGNED_SHORT : COGL_INDICES_TYPE_UNSIGNED_INT, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; cogl_indices_set_offset(indices, sizeof(ImDrawIdx) * idx_buffer_offset); cogl_primitive_set_indices(primitive, indices, pcmd->ElemCount); if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { bool has_texture = pcmd->TextureId != NULL; CoglPipeline *pipeline = has_texture ? (cogl_is_pipeline(pcmd->TextureId) ? (CoglPipeline *) pcmd->TextureId : g_ImagePipeline) : g_ColorPipeline; if (has_texture && pipeline == g_ImagePipeline) { cogl_pipeline_set_layer_texture(g_ImagePipeline, 0, COGL_TEXTURE(pcmd->TextureId)); } cogl_framebuffer_push_scissor_clip(g_Framebuffer, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z - pcmd->ClipRect.x, pcmd->ClipRect.w - pcmd->ClipRect.y); cogl_primitive_draw(primitive, g_Framebuffer, pipeline); cogl_framebuffer_pop_clip(g_Framebuffer); } idx_buffer_offset += pcmd->ElemCount; } for (int i = 0; i < 3; i++) cogl_object_unref(attrs[i]); cogl_object_unref(primitive); cogl_object_unref(vertices); cogl_object_unref(indices); } } static const char* ImGui_ImplGtk3Cogl_GetClipboardText(void* user_data) { static char *last_clipboard = NULL; g_clear_pointer(&last_clipboard, g_free); last_clipboard = gtk_clipboard_wait_for_text(GTK_CLIPBOARD(user_data)); return last_clipboard; } static void ImGui_ImplGtk3Cogl_SetClipboardText(void* user_data, const char* text) { gtk_clipboard_set_text(GTK_CLIPBOARD(user_data), text, -1); } bool ImGui_ImplGtk3Cogl_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. g_clear_pointer(&io.Fonts->TexID, cogl_object_unref); io.Fonts->TexID = cogl_texture_2d_new_from_data(g_Context, width, height, COGL_PIXEL_FORMAT_RGBA_8888, width * 4, pixels, NULL); return true; } bool ImGui_ImplGtk3Cogl_CreateDeviceObjects() { g_ColorPipeline = cogl_pipeline_new(g_Context); g_ImagePipeline = cogl_pipeline_new(g_Context); CoglError *error = NULL; if (!cogl_pipeline_set_blend(g_ColorPipeline, "RGB = ADD(SRC_COLOR*(SRC_COLOR[A]), DST_COLOR*(1-SRC_COLOR[A]))" "A = ADD(SRC_COLOR[A], DST_COLOR*(1-SRC_COLOR[A]))", &error)) { g_warning("Blending: %s", error->message); g_error_free(error); return false; } cogl_pipeline_set_cull_face_mode(g_ColorPipeline, COGL_PIPELINE_CULL_FACE_MODE_NONE); CoglDepthState depth_state; cogl_depth_state_init(&depth_state); cogl_depth_state_set_test_enabled(&depth_state, FALSE); if (!cogl_pipeline_set_depth_state(g_ColorPipeline, &depth_state, &error)) { g_warning("Depth: %s", error->message); g_error_free(error); return false; } if (!cogl_pipeline_set_blend(g_ImagePipeline, "RGB = ADD(SRC_COLOR*(SRC_COLOR[A]), DST_COLOR*(1-SRC_COLOR[A]))" "A = ADD(SRC_COLOR[A], DST_COLOR*(1-SRC_COLOR[A]))", &error)) { g_warning("Blending: %s", error->message); g_error_free(error); return false; } cogl_pipeline_set_cull_face_mode(g_ImagePipeline, COGL_PIPELINE_CULL_FACE_MODE_NONE); if (!cogl_pipeline_set_depth_state(g_ImagePipeline, &depth_state, &error)) { g_warning("Depth: %s", error->message); g_error_free(error); return false; } ImGui_ImplGtk3Cogl_CreateFontsTexture(); /* Disable depth buffer since we're not using it. */ //cogl_framebuffer_set_depth_write_enabled(g_Framebuffer, FALSE); return true; } void ImGui_ImplGtk3Cogl_InvalidateDeviceObjects() { g_clear_pointer(&g_ColorPipeline, cogl_object_unref); g_clear_pointer(&g_ImagePipeline, cogl_object_unref); g_clear_pointer(&ImGui::GetIO().Fonts->TexID, cogl_object_unref); } void ImGui_ImplGtk3Cogl_HandleEvent(GdkEvent *event) { ImGuiIO& io = ImGui::GetIO(); GdkEventType type = gdk_event_get_event_type(event); switch (type) { case GDK_MOTION_NOTIFY: { gdouble x = 0.0f, y = 0.0f; if (gdk_event_get_coords(event, &x, &y)) g_MousePosition = ImVec2(x, y); break; } case GDK_BUTTON_PRESS: case GDK_BUTTON_RELEASE: { guint button = 0; if (gdk_event_get_button(event, &button) && button > 0 && button <= 5) { if (type == GDK_BUTTON_PRESS) g_MousePressed[button - 1] = true; } break; } case GDK_SCROLL: { gdouble x, y; if (gdk_event_get_scroll_deltas(event, &x, &y)) g_MouseWheel = -y; break; } case GDK_KEY_PRESS: case GDK_KEY_RELEASE: { GdkEventKey *e = (GdkEventKey *) event; static const struct { enum ImGuiKey_ imgui; guint gdk; } gdk_key_to_imgui_key[] = { { ImGuiKey_Tab, GDK_KEY_Tab }, { ImGuiKey_Tab, GDK_KEY_ISO_Left_Tab }, { ImGuiKey_LeftArrow, GDK_KEY_Left }, { ImGuiKey_RightArrow, GDK_KEY_Right }, { ImGuiKey_UpArrow, GDK_KEY_Up }, { ImGuiKey_DownArrow, GDK_KEY_Down }, { ImGuiKey_PageUp, GDK_KEY_Page_Up }, { ImGuiKey_PageDown, GDK_KEY_Page_Down }, { ImGuiKey_Home, GDK_KEY_Home }, { ImGuiKey_End, GDK_KEY_End }, { ImGuiKey_Delete, GDK_KEY_Delete }, { ImGuiKey_Backspace, GDK_KEY_BackSpace }, { ImGuiKey_Space, GDK_KEY_space }, { ImGuiKey_Enter, GDK_KEY_Return }, { ImGuiKey_Escape, GDK_KEY_Escape }, { ImGuiKey_A, GDK_KEY_a }, { ImGuiKey_C, GDK_KEY_c }, { ImGuiKey_V, GDK_KEY_v }, { ImGuiKey_X, GDK_KEY_x }, { ImGuiKey_Y, GDK_KEY_y }, { ImGuiKey_Z, GDK_KEY_z }, }; for (unsigned i = 0; i < ARRAY_SIZE(gdk_key_to_imgui_key); i++) { if (e->keyval == gdk_key_to_imgui_key[i].gdk) io.KeysDown[gdk_key_to_imgui_key[i].imgui] = type == GDK_KEY_PRESS; } gunichar c = gdk_keyval_to_unicode(e->keyval); if (g_unichar_isprint(c) && ImGuiKey_COUNT + c < ARRAY_SIZE(io.KeysDown)) io.KeysDown[ImGuiKey_COUNT + c] = type == GDK_KEY_PRESS; if (type == GDK_KEY_PRESS && e->string) io.AddInputCharactersUTF8(e->string); struct { bool *var; GdkModifierType modifier; guint keyvals[3]; } mods[] = { { &io.KeyCtrl, GDK_CONTROL_MASK, { GDK_KEY_Control_L, GDK_KEY_Control_R, 0 }, }, { &io.KeyShift, GDK_SHIFT_MASK, { GDK_KEY_Shift_L, GDK_KEY_Shift_R, 0 }, }, { &io.KeyAlt, GDK_MOD1_MASK, { GDK_KEY_Alt_L, GDK_KEY_Alt_R, 0 }, }, { &io.KeySuper, GDK_SUPER_MASK, { GDK_KEY_Super_L, GDK_KEY_Super_R, 0 }, } }; for (unsigned i = 0; i < ARRAY_SIZE(mods); i++) { *mods[i].var = (mods[i].modifier & e->state); bool match = false; for (int j = 0; mods[i].keyvals[j] != 0; j++) if (e->keyval == mods[i].keyvals[j]) match = true; if (match) *mods[i].var = type == GDK_KEY_PRESS; } break; } default: break; } // We trigger 2 subsequent redraws for each event because of the // way some ImGui widgets work. For example a Popup menu will only // appear a frame after a click happened. g_NumRedraws = 2; GdkFrameClock *clock = gdk_window_get_frame_clock(g_GdkWindow); gdk_frame_clock_request_phase(clock, GDK_FRAME_CLOCK_PHASE_PAINT); } static gboolean handle_gdk_event(GtkWidget *widget, GdkEvent *event, void *data) { ImGui_ImplGtk3Cogl_HandleEvent(event); return TRUE; } static void handle_allocate(GtkWidget *widget, GdkRectangle *allocation, gpointer user_data) { gdk_window_resize(g_GdkWindow, allocation->width, allocation->height); g_Callbacks->resize(g_GdkWindow, COGL_ONSCREEN(g_Framebuffer), allocation->width, allocation->height, allocation->x, allocation->y); } static void handle_repaint(GdkFrameClock *clock, void *data) { g_Callback(COGL_ONSCREEN(g_Framebuffer), g_CallbackData); } CoglOnscreen* ImGui_ImplGtk3Cogl_Init(GtkWidget* widget, void (*callback)(CoglOnscreen *onscreen, void *data), void *data) { g_clear_pointer(&g_GtkWidget, g_object_unref); g_clear_pointer(&g_GdkWindow, g_object_unref); g_clear_pointer(&g_Framebuffer, cogl_object_unref); g_clear_pointer(&g_Context, cogl_object_unref); g_GtkWidget = GTK_WIDGET(g_object_ref(widget)); gtk_widget_realize(widget); GdkWindow *parent_window = gtk_widget_get_window(widget); GtkAllocation allocation; gtk_widget_get_allocation(widget, &allocation); g_Callbacks = get_backend_callbacks(parent_window); GdkWindowAttr attributes; memset(&attributes, 0, sizeof(attributes)); attributes.x = 0; attributes.y = 0; attributes.width = allocation.width; attributes.height = allocation.height; attributes.wclass = GDK_INPUT_OUTPUT; attributes.window_type = g_Callbacks->winsys == COGL_WINSYS_ID_EGL_WAYLAND ? GDK_WINDOW_SUBSURFACE : GDK_WINDOW_CHILD; GdkDisplay *display = gdk_window_get_display(parent_window); attributes.visual = gtk_widget_get_visual(widget); g_GdkWindow = gdk_window_new(parent_window, &attributes, GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL); gdk_window_set_transient_for(g_GdkWindow, parent_window); gdk_window_set_pass_through(g_GdkWindow, TRUE); cairo_rectangle_int_t empty_rect; memset(&empty_rect, 0, sizeof(empty_rect)); cairo_region_t *input_region = cairo_region_create_rectangle(&empty_rect); gdk_window_input_shape_combine_region(g_GdkWindow, input_region, 0, 0); cairo_region_destroy(input_region); cairo_region_t *region = get_window_region(g_GdkWindow); gdk_window_set_opaque_region(g_GdkWindow, region); cairo_region_destroy(region); CoglRenderer *renderer = cogl_renderer_new(); cogl_renderer_set_winsys_id(renderer, g_Callbacks->winsys); g_Callbacks->init(renderer, display, g_GdkWindow); gdk_window_ensure_native(g_GdkWindow); g_Context = cogl_context_new(cogl_display_new(renderer, NULL), NULL); CoglOnscreen *onscreen = cogl_onscreen_new(g_Context, 1, 1); cogl_object_unref(renderer); g_Callbacks->resize(g_GdkWindow, onscreen, allocation.width, allocation.height, allocation.x, allocation.y); gtk_widget_add_events(widget, EVENT_MASK); g_signal_connect(widget, "event", G_CALLBACK(handle_gdk_event), NULL); g_signal_connect(widget, "size-allocate", G_CALLBACK(handle_allocate), NULL); g_Callbacks->set_window(onscreen, g_GdkWindow); if (!cogl_framebuffer_allocate(COGL_FRAMEBUFFER(onscreen), NULL)) g_warning("Unable to allocate framebuffer"); g_Framebuffer = COGL_FRAMEBUFFER(onscreen); ImGuiIO& io = ImGui::GetIO(); for (int i = 0; i < ImGuiKey_COUNT; i++) { io.KeyMap[i] = i; } io.SetClipboardTextFn = ImGui_ImplGtk3Cogl_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplGtk3Cogl_GetClipboardText; io.ClipboardUserData = gtk_widget_get_clipboard(g_GtkWidget, GDK_SELECTION_CLIPBOARD); g_Callback = callback; g_CallbackData = data; GdkFrameClock *clock = gdk_window_get_frame_clock(g_GdkWindow); g_signal_connect(clock, "paint", G_CALLBACK(handle_repaint), NULL); gdk_frame_clock_request_phase(clock, GDK_FRAME_CLOCK_PHASE_PAINT); gdk_window_show(g_GdkWindow); return COGL_ONSCREEN(g_Framebuffer); } CoglContext* ImGui_ImplGtk3Cogl_GetContext() { return g_Context; } void ImGui_ImplGtk3Cogl_Shutdown() { ImGui_ImplGtk3Cogl_InvalidateDeviceObjects(); g_clear_pointer(&g_Framebuffer, cogl_object_unref); g_clear_pointer(&g_Context, cogl_object_unref); } static gboolean timeout_callback(gpointer data) { GdkFrameClock *clock = gdk_window_get_frame_clock(g_GdkWindow); gdk_frame_clock_request_phase(clock, GDK_FRAME_CLOCK_PHASE_PAINT); g_RedrawTimeout = 0; return FALSE; } static void kick_timeout_redraw(float timeout) { if (g_RedrawTimeout) return; g_RedrawTimeout = g_timeout_add(timeout * 1000, timeout_callback, NULL); } void ImGui_ImplGtk3Cogl_NewFrame() { if (!g_ColorPipeline) ImGui_ImplGtk3Cogl_CreateDeviceObjects(); bool next_redraw = false; if (g_NumRedraws > 0) { GdkFrameClock *clock = gdk_window_get_frame_clock(g_GdkWindow); gdk_frame_clock_request_phase(clock, GDK_FRAME_CLOCK_PHASE_PAINT); g_NumRedraws--; next_redraw = true; } ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; gdk_window_get_geometry(g_GdkWindow, NULL, NULL, &w, &h); io.DisplaySize = ImVec2((float)w, (float)h); io.DisplayFramebufferScale = g_Callbacks->get_scale(g_GdkWindow); // Setup time step guint64 current_time = g_get_monotonic_time(); io.DeltaTime = g_Time > 0 ? ((float)(current_time - g_Time) / 1000000) : (float)(1.0f/60.0f); g_Time = current_time; // Setup inputs if (gdk_window_get_state(g_GdkWindow) & GDK_WINDOW_STATE_FOCUSED) { io.MousePos = g_MousePosition; // Mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.) } else { io.MousePos = ImVec2(-1,-1); } GdkDevice *pointer = gdk_device_manager_get_client_pointer(gdk_display_get_device_manager(gdk_display_get_default())); GdkModifierType modifiers; gdk_device_get_state(pointer, g_GdkWindow, NULL, &modifiers); for (int i = 0; i < 3; i++) { io.MouseDown[i] = g_MousePressed[i] || (modifiers & (GDK_BUTTON1_MASK << i)) != 0; g_MousePressed[i] = false; } io.MouseWheel = g_MouseWheel; g_MouseWheel = 0.0f; // Hide OS mouse cursor if ImGui is drawing it GdkDisplay *display = gdk_window_get_display(g_GdkWindow); GdkCursor *cursor = gdk_cursor_new_from_name(display, io.MouseDrawCursor ? "none" : "default"); gdk_window_set_cursor(g_GdkWindow, cursor); g_object_unref(cursor); // Start the frame ImGui::NewFrame(); if (!next_redraw && io.WantTextInput) kick_timeout_redraw(0.2); } void ImGui_ImplGtk3Cogl_ScheduleFrame() { GdkFrameClock *clock = gdk_window_get_frame_clock(g_GdkWindow); gdk_frame_clock_request_phase(clock, GDK_FRAME_CLOCK_PHASE_PAINT); } ================================================ FILE: ui/imgui/imgui_impl_gtk3_cogl.h ================================================ // ImGui Gtk3 binding with Cogl // 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 #define COGL_ENABLE_EXPERIMENTAL_API 1 #include IMGUI_API CoglOnscreen* ImGui_ImplGtk3Cogl_Init(GtkWidget* widget, void (*callback)(CoglOnscreen *, void *), void *data); IMGUI_API void ImGui_ImplGtk3Cogl_HandleEvent(GdkEvent *event); IMGUI_API CoglContext* ImGui_ImplGtk3Cogl_GetContext(); IMGUI_API void ImGui_ImplGtk3Cogl_Shutdown(); IMGUI_API void ImGui_ImplGtk3Cogl_NewFrame(); IMGUI_API void ImGui_ImplGtk3Cogl_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing ImGui state. IMGUI_API void ImGui_ImplGtk3Cogl_InvalidateDeviceObjects(); IMGUI_API bool ImGui_ImplGtk3Cogl_CreateDeviceObjects(); IMGUI_API void ImGui_ImplGtk3Cogl_ScheduleFrame(); ================================================ FILE: ui/imgui/imgui_impl_sdl_gles2.cpp ================================================ // ImGui SDL2 binding with OpenGL2 ES // 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_sdl_gles2.h" // SDL,OpenGLES2 #include #include #ifdef __APPLE__ #include #include #else #include #endif #ifdef EMSCRIPTEN #include #endif // Data 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_ElementsHandle = 0; static void (*g_Callback)(void *data); static void* g_CallbackData; static int g_NumRedraws = 0; // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. // 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_ImplSdlGLES2_RenderDrawData(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 GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture); glActiveTexture(GL_TEXTURE0); GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_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_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb); GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb); GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha); GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha); GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb); GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha); 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, polygon fill 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); // 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]); 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 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), (const 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), (const 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 glDisableVertexAttribArray(g_AttribLocationPosition); glDisableVertexAttribArray(g_AttribLocationUV); glDisableVertexAttribArray(g_AttribLocationColor); glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); glActiveTexture(last_active_texture); 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); glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); 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_ImplSdlGLES2_GetClipboardText(void*) { return SDL_GetClipboardText(); } static void ImGui_ImplSdlGLES2_SetClipboardText(void*, const char* text) { SDL_SetClipboardText(text); } bool ImGui_ImplSdlGLES2_ProcessEvent(SDL_Event* event) { ImGuiIO& io = ImGui::GetIO(); bool handled = true; switch (event->type) { case SDL_MOUSEWHEEL: { if (event->wheel.y > 0) g_MouseWheel = 1; if (event->wheel.y < 0) g_MouseWheel = -1; break; } case SDL_MOUSEBUTTONDOWN: { if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true; if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true; if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true; break; } case SDL_MOUSEBUTTONUP: { /* Make sure we trigger a redraw. */ break; } case SDL_TEXTINPUT: { io.AddInputCharactersUTF8(event->text.text); break; } case SDL_KEYDOWN: case SDL_KEYUP: { int key = event->key.keysym.sym & ~SDLK_SCANCODE_MASK; io.KeysDown[key] = (event->type == SDL_KEYDOWN); io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0); break; } default: { handled = false; break; } } if (handled) { // We trigger 2 subsequent redraws for each event because of the // way some ImGui widgets work. For example a Popup menu will only // appear a frame after a click happened. g_NumRedraws = 2; } return handled; } void ImGui_ImplSdlGLES2_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 for OpenGL3 demo because it is more likely to be compatible with user's existing shader. // 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); } bool ImGui_ImplSdlGLES2_CreateDeviceObjects() { // Backup GL state GLint last_texture, last_array_buffer; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); const GLchar *vertex_shader = "uniform mat4 ProjMtx;\n" "attribute vec2 Position;\n" "attribute vec2 UV;\n" "attribute vec4 Color;\n" "varying vec2 Frag_UV;\n" "varying 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 = "precision mediump float;\n" "uniform sampler2D Texture;\n" "varying vec2 Frag_UV;\n" "varying vec4 Frag_Color;\n" "void main()\n" "{\n" " gl_FragColor = Frag_Color * texture2D( 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); ImGui_ImplSdlGLES2_CreateFontsTexture(); // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); return true; } void ImGui_ImplSdlGLES2_InvalidateDeviceObjects() { if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle); if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle); 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; } } static int sdl_event_callback(void *userdata, SDL_Event *event) { ImGui_ImplSdlGLES2_ScheduleFrame(); return 0; } bool ImGui_ImplSdlGLES2_Init(SDL_Window* window, void (*callback)(void *), void *data) { ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE; io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE; io.KeyMap[ImGuiKey_Space] = SDLK_SPACE; io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN; io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE; io.KeyMap[ImGuiKey_A] = SDLK_a; io.KeyMap[ImGuiKey_C] = SDLK_c; io.KeyMap[ImGuiKey_V] = SDLK_v; io.KeyMap[ImGuiKey_X] = SDLK_x; io.KeyMap[ImGuiKey_Y] = SDLK_y; io.KeyMap[ImGuiKey_Z] = SDLK_z; io.SetClipboardTextFn = ImGui_ImplSdlGLES2_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplSdlGLES2_GetClipboardText; io.ClipboardUserData = NULL; #ifdef _WIN32 SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(window, &wmInfo); io.ImeWindowHandle = wmInfo.info.win.window; #else (void)window; #endif g_Callback = callback; g_CallbackData = data; SDL_AddEventWatch(sdl_event_callback, NULL); ImGui_ImplSdlGLES2_ScheduleFrame(); return true; } void ImGui_ImplSdlGLES2_Shutdown() { ImGui_ImplSdlGLES2_InvalidateDeviceObjects(); } static bool g_Scheduled = false; static void schedule_callback(void *data) { g_Scheduled = false; if (g_Callback) g_Callback(g_CallbackData); } static void ImGui_ImplSdlGLES2_ScheduleFrame(int ms) { if (!g_Scheduled) { emscripten_async_call(schedule_callback, NULL, ms); g_Scheduled = true; } } void ImGui_ImplSdlGLES2_ScheduleFrame() { ImGui_ImplSdlGLES2_ScheduleFrame(-1); } void ImGui_ImplSdlGLES2_NewFrame(SDL_Window* window) { if (!g_FontTexture) ImGui_ImplSdlGLES2_CreateDeviceObjects(); bool next_redraw = false; if (g_NumRedraws > 0) { ImGui_ImplSdlGLES2_ScheduleFrame(); g_NumRedraws--; next_redraw = true; } ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(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 Uint32 time = SDL_GetTicks(); double current_time = time / 1000.0; 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 SDL_PollEvent()) int mx, my; Uint32 mouseMask = SDL_GetMouseState(&mx, &my); if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS) io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) else io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 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. io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false; io.MouseWheel = g_MouseWheel; g_MouseWheel = 0.0f; // Hide OS mouse cursor if ImGui is drawing it SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1); // Start the frame ImGui::NewFrame(); if (!next_redraw && io.WantTextInput) ImGui_ImplSdlGLES2_ScheduleFrame(200); } ================================================ FILE: ui/imgui/imgui_impl_sdl_gles2.h ================================================ // ImGui SDL2 binding with OpenGL ES2 // 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 SDL_Window; typedef union SDL_Event SDL_Event; IMGUI_API bool ImGui_ImplSdlGLES2_Init(SDL_Window* window, void (*callback)(void *), void *data); IMGUI_API void ImGui_ImplSdlGLES2_Shutdown(); IMGUI_API void ImGui_ImplSdlGLES2_NewFrame(SDL_Window* window); IMGUI_API bool ImGui_ImplSdlGLES2_ProcessEvent(SDL_Event* event); IMGUI_API void ImGui_ImplSdlGLES2_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing ImGui state. IMGUI_API void ImGui_ImplSdlGLES2_InvalidateDeviceObjects(); IMGUI_API bool ImGui_ImplSdlGLES2_CreateDeviceObjects(); IMGUI_API void ImGui_ImplSdlGLES2_ScheduleFrame(); ================================================ FILE: ui/imgui/imgui_internal.h ================================================ // dear imgui, v1.60 WIP // (internals) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! // Set: // #define IMGUI_DEFINE_MATH_OPERATORS // To implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators) #pragma once #ifndef IMGUI_VERSION #error Must include imgui.h before imgui_internal.h #endif #include // FILE* #include // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf #include // INT_MIN, INT_MAX #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 ImGuiMenuColumns; struct ImGuiDrawContext; struct ImGuiTextEditState; struct ImGuiPopupRef; struct ImGuiWindow; struct ImGuiWindowSettings; typedef int ImGuiLayoutType; // enum: horizontal or vertical // enum ImGuiLayoutType_ typedef int ImGuiButtonFlags; // flags: for ButtonEx(), ButtonBehavior() // enum ImGuiButtonFlags_ typedef int ImGuiItemFlags; // flags: for PushItemFlag() // enum ImGuiItemFlags_ typedef int ImGuiItemStatusFlags; // flags: storage for DC.LastItemXXX // enum ImGuiItemStatusFlags_ typedef int ImGuiNavHighlightFlags; // flags: for RenderNavHighlight() // enum ImGuiNavHighlightFlags_ typedef int ImGuiNavDirSourceFlags; // flags: for GetNavInputAmount2d() // enum ImGuiNavDirSourceFlags_ typedef int ImGuiSeparatorFlags; // flags: for Separator() - internal // enum ImGuiSeparatorFlags_ typedef int ImGuiSliderFlags; // flags: for SliderBehavior() // 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 //----------------------------------------------------------------------------- #ifndef GImGui extern IMGUI_API ImGuiContext* GImGui; // Current implicit ImGui context pointer #endif //----------------------------------------------------------------------------- // Helpers //----------------------------------------------------------------------------- #define IM_PI 3.14159265358979323846f // 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* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0); IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode); static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; } static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 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; } // Helpers: Geometry IMGUI_API ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p); IMGUI_API bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p); IMGUI_API ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p); IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w); // Helpers: String IMGUI_API int ImStricmp(const char* str1, const char* str2); IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count); IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count); IMGUI_API char* ImStrdup(const char* str); IMGUI_API char* ImStrchrRange(const char* str_begin, const char* str_end, char c); 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, size_t buf_size, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) IM_FMTLIST(3); // 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); } 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); } 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(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); } static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? 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 void ImSwap(int& a, int& b) { int tmp = a; a = b; b = tmp; } static inline void ImSwap(float& a, float& b) { float tmp = a; a = b; b = tmp; } static inline int ImLerp(int a, int b, float t) { return (int)(a + (b - a) * t); } 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, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * 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 ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); } 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(const ImVec2& v) { return ImVec2((float)(int)v.x, (float)(int)v.y); } static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } static inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; } static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.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 which on some platforms complains when user has disabled exceptions. struct ImNewPlacementDummy {}; inline void* operator new(size_t, ImNewPlacementDummy, void* ptr) { return ptr; } inline void operator delete(void*, ImNewPlacementDummy, void*) {} // This is only required so we can use the symetrical new() #define IM_PLACEMENT_NEW(_PTR) new(ImNewPlacementDummy(), _PTR) #define IM_NEW(_TYPE) new(ImNewPlacementDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE template void IM_DELETE(T*& p) { if (p) { p->~T(); ImGui::MemFree(p); p = NULL; } } //----------------------------------------------------------------------------- // Types //----------------------------------------------------------------------------- enum ImGuiButtonFlags_ { ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // return true on click + release on same item [DEFAULT if no PressedOn* flag is set] ImGuiButtonFlags_PressedOnClick = 1 << 2, // return true on click (default requires click+release) ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return true on release (default requires click+release) ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return true on double-click (default requires click+release) ImGuiButtonFlags_FlattenChildren = 1 << 5, // allow interactions even if a child window is overlapping ImGuiButtonFlags_AllowItemOverlap = 1 << 6, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap() ImGuiButtonFlags_DontClosePopups = 1 << 7, // disable automatically closing parent popup on press // [UNUSED] ImGuiButtonFlags_Disabled = 1 << 8, // disable interactions ImGuiButtonFlags_AlignTextBaseLine = 1 << 9, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine ImGuiButtonFlags_NoKeyModifiers = 1 << 10, // disable interaction if a key modifier is held ImGuiButtonFlags_NoHoldingActiveID = 1 << 11, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) ImGuiButtonFlags_PressedOnDragDropHold = 1 << 12, // press when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) ImGuiButtonFlags_NoNavFocus = 1 << 13 // don't override navigation focus when activated }; enum ImGuiSliderFlags_ { ImGuiSliderFlags_Vertical = 1 << 0 }; enum ImGuiColumnsFlags_ { // Default: 0 ImGuiColumnsFlags_NoBorder = 1 << 0, // Disable column dividers ImGuiColumnsFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers ImGuiColumnsFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns ImGuiColumnsFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window ImGuiColumnsFlags_GrowParentContentsSize= 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. }; enum ImGuiSelectableFlagsPrivate_ { // NB: need to be in sync with last value of ImGuiSelectableFlags_ ImGuiSelectableFlags_Menu = 1 << 3, // -> PressedOnClick ImGuiSelectableFlags_MenuItem = 1 << 4, // -> PressedOnRelease ImGuiSelectableFlags_Disabled = 1 << 5, ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 6 }; enum ImGuiSeparatorFlags_ { ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar ImGuiSeparatorFlags_Vertical = 1 << 1 }; // Storage for LastItem data enum ImGuiItemStatusFlags_ { ImGuiItemStatusFlags_HoveredRect = 1 << 0, ImGuiItemStatusFlags_HasDisplayRect = 1 << 1 }; // FIXME: this is in development, not exposed/functional as a generic feature yet. enum ImGuiLayoutType_ { ImGuiLayoutType_Vertical, ImGuiLayoutType_Horizontal }; enum ImGuiAxis { ImGuiAxis_None = -1, ImGuiAxis_X = 0, ImGuiAxis_Y = 1 }; enum ImGuiPlotType { ImGuiPlotType_Lines, ImGuiPlotType_Histogram }; enum ImGuiDataType { ImGuiDataType_Int, ImGuiDataType_Float, ImGuiDataType_Float2 }; enum ImGuiDir { ImGuiDir_None = -1, ImGuiDir_Left = 0, ImGuiDir_Right = 1, ImGuiDir_Up = 2, ImGuiDir_Down = 3, ImGuiDir_Count_ }; enum ImGuiInputSource { ImGuiInputSource_None = 0, ImGuiInputSource_Mouse, ImGuiInputSource_Nav, ImGuiInputSource_NavKeyboard, // Only used occasionally for storage, not tested/handled by most code ImGuiInputSource_NavGamepad, // " ImGuiInputSource_Count_, }; // FIXME-NAV: Clarify/expose various repeat delay/rate enum ImGuiInputReadMode { ImGuiInputReadMode_Down, ImGuiInputReadMode_Pressed, ImGuiInputReadMode_Released, ImGuiInputReadMode_Repeat, ImGuiInputReadMode_RepeatSlow, ImGuiInputReadMode_RepeatFast }; enum ImGuiNavHighlightFlags_ { ImGuiNavHighlightFlags_TypeDefault = 1 << 0, ImGuiNavHighlightFlags_TypeThin = 1 << 1, ImGuiNavHighlightFlags_AlwaysDraw = 1 << 2, ImGuiNavHighlightFlags_NoRounding = 1 << 3 }; enum ImGuiNavDirSourceFlags_ { ImGuiNavDirSourceFlags_Keyboard = 1 << 0, ImGuiNavDirSourceFlags_PadDPad = 1 << 1, ImGuiNavDirSourceFlags_PadLStick = 1 << 2 }; enum ImGuiNavForward { ImGuiNavForward_None, ImGuiNavForward_ForwardQueued, ImGuiNavForward_ForwardActive }; // 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& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; } void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.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 Translate(const ImVec2& v) { Min.x += v.x; Min.y += v.y; Max.x += v.x; Max.y += v.y; } void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. 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; } void FixInverted() { if (Min.x > Max.x) ImSwap(Min.x, Max.x); if (Min.y > Max.y) ImSwap(Min.y, Max.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } bool IsFinite() const { return Min.x != FLT_MAX; } }; // 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; }; // Simple column measurement currently used for MenuItem() only. This is very short-sighted/throw-away code and NOT a generic helper. struct IMGUI_API ImGuiMenuColumns { int Count; float Spacing; float Width, NextWidth; float Pos[4], NextWidths[4]; ImGuiMenuColumns(); 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 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 InitialText; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) ImVector 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.cursor = StbState.select_end = CurLenW; StbState.has_preferred_x = false; } void OnKeyPressed(int key); }; // Data saved in imgui.ini file struct ImGuiWindowSettings { char* Name; ImGuiID Id; ImVec2 Pos; ImVec2 Size; bool Collapsed; ImGuiWindowSettings() { Name = NULL; Id = 0; Pos = Size = ImVec2(0,0); Collapsed = false; } }; struct ImGuiSettingsHandler { const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' ImGuiID TypeHash; // == ImHash(TypeName, 0, 0) void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); void* UserData; ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } }; // 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() int OpenFrameCount; // Set on OpenPopup() ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differenciate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup }; struct ImGuiColumnData { float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) float OffsetNormBeforeResize; ImGuiColumnsFlags Flags; // Not exposed ImRect ClipRect; ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = 0; } }; struct ImGuiColumnsSet { ImGuiID ID; ImGuiColumnsFlags Flags; bool IsFirstFrame; bool IsBeingResized; int Current; int Count; float MinX, MaxX; float StartPosY; float StartMaxPosX; // Backup of CursorMaxPos float CellMinY, CellMaxY; ImVector Columns; ImGuiColumnsSet() { Clear(); } void Clear() { ID = 0; Flags = 0; IsFirstFrame = false; IsBeingResized = false; Current = 0; Count = 1; MinX = MaxX = 0.0f; StartPosY = 0.0f; StartMaxPosX = 0.0f; CellMinY = CellMaxY = 0.0f; Columns.clear(); } }; struct IMGUI_API ImDrawListSharedData { ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas ImFont* Font; // Current/default font (optional, for simplified AddText overload) float FontSize; // Current/default font size (optional, for simplified AddText overload) float CurveTessellationTol; ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() // Const data // FIXME: Bake rounded corners fill/borders in atlas ImVec2 CircleVtx12[12]; ImDrawListSharedData(); }; struct ImDrawDataBuilder { ImVector Layers[2]; // Global layers for: regular, tooltip void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].resize(0); } void ClearFreeMemory() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].clear(); } IMGUI_API void FlattenIntoSingleLayer(); }; struct ImGuiNavMoveResult { ImGuiID ID; // Best candidate ImGuiID ParentID; // Best candidate window->IDStack.back() - to compare context ImGuiWindow* Window; // Best candidate window float DistBox; // Best candidate box distance to current NavId float DistCenter; // Best candidate center distance to current NavId float DistAxial; ImRect RectRel; // Best candidate bounding box in window relative space ImGuiNavMoveResult() { Clear(); } void Clear() { ID = ParentID = 0; Window = NULL; DistBox = DistCenter = DistAxial = FLT_MAX; RectRel = ImRect(); } }; // Storage for SetNexWindow** functions struct ImGuiNextWindowData { ImGuiCond PosCond; ImGuiCond SizeCond; ImGuiCond ContentSizeCond; ImGuiCond CollapsedCond; ImGuiCond SizeConstraintCond; ImGuiCond FocusCond; ImGuiCond BgAlphaCond; ImVec2 PosVal; ImVec2 PosPivotVal; ImVec2 SizeVal; ImVec2 ContentSizeVal; bool CollapsedVal; ImRect SizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true ImGuiSizeCallback SizeCallback; void* SizeCallbackUserData; float BgAlphaVal; ImGuiNextWindowData() { PosCond = SizeCond = ContentSizeCond = CollapsedCond = SizeConstraintCond = FocusCond = BgAlphaCond = 0; PosVal = PosPivotVal = SizeVal = ImVec2(0.0f, 0.0f); ContentSizeVal = ImVec2(0.0f, 0.0f); CollapsedVal = false; SizeConstraintRect = ImRect(); SizeCallback = NULL; SizeCallbackUserData = NULL; BgAlphaVal = FLT_MAX; } void Clear() { PosCond = SizeCond = ContentSizeCond = CollapsedCond = SizeConstraintCond = FocusCond = BgAlphaCond = 0; } }; // Main state for ImGui struct ImGuiContext { bool Initialized; bool FontAtlasOwnedByContext; // Io.Fonts-> is owned by the ImGuiContext and will be destructed along with it. ImGuiIO IO; ImGuiStyle Style; ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. ImDrawListSharedData DrawListSharedData; float Time; int FrameCount; int FrameCountEnded; int FrameCountRendered; ImVector Windows; ImVector WindowsSortBuffer; ImVector CurrentWindowStack; ImGuiStorage WindowsById; int WindowsActiveCount; ImGuiWindow* CurrentWindow; // Being drawn into ImGuiWindow* HoveredWindow; // Will catch mouse inputs ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) ImGuiID HoveredId; // Hovered widget bool HoveredIdAllowOverlap; ImGuiID HoveredIdPreviousFrame; float HoveredIdTimer; ImGuiID ActiveId; // Active widget ImGuiID ActiveIdPreviousFrame; float ActiveIdTimer; bool ActiveIdIsAlive; // Active widget has been seen this frame bool ActiveIdIsJustActivated; // Set at the time of activation for one frame bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) int ActiveIdAllowNavDirFlags; // Active widget allows using directional navigation (e.g. can activate a button and move away from it) ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) ImGuiWindow* ActiveIdWindow; ImGuiInputSource ActiveIdSource; // Activating with mouse or nav (gamepad/keyboard) ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow. ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() ImVector FontStack; // Stack for PushFont()/PopFont() ImVector OpenPopupStack; // Which popups are open (persistent) ImVector CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame) ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions bool NextTreeNodeOpenVal; // Storage for SetNextTreeNode** functions ImGuiCond NextTreeNodeOpenCond; // Navigation data (for gamepad/keyboard) ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusWindow' ImGuiID NavId; // Focused item for navigation ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0, also set when calling ActivateItem() ImGuiID NavActivateDownId; // ~~ IsNavInputDown(ImGuiNavInput_Activate) ? NavId : 0 ImGuiID NavActivatePressedId; // ~~ IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0 ImGuiID NavInputId; // ~~ IsNavInputPressed(ImGuiNavInput_Input) ? NavId : 0 ImGuiID NavJustTabbedId; // Just tabbed to this id. ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest) ImRect NavScoringRectScreen; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring. int NavScoringCount; // Metrics for debugging ImGuiWindow* NavWindowingTarget; // When selecting a window (holding Menu+FocusPrev/Next, or equivalent of CTRL-TAB) this window is temporarily displayed front-most. float NavWindowingHighlightTimer; float NavWindowingHighlightAlpha; bool NavWindowingToggleLayer; ImGuiInputSource NavWindowingInputSource; // Gamepad or keyboard mode int NavLayer; // Layer we are navigating on. For now the system is hard-coded for 0=main contents and 1=menu/title bar, may expose layers later. int NavIdTabCounter; // == NavWindow->DC.FocusIdxTabCounter at time of NavId processing bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRefRectRel is valid bool NavMousePosDirty; // When set we will update mouse position if (NavFlags & ImGuiNavFlags_MoveMouse) if set (NB: this not enabled by default) bool NavDisableHighlight; // When user starts using mouse, we hide gamepad/keyboard highlight (nb: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover) bool NavDisableMouseHover; // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again. bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest bool NavInitRequest; // Init request for appearing window to select first item bool NavInitRequestFromMove; ImGuiID NavInitResultId; ImRect NavInitResultRectRel; bool NavMoveFromClampedRefRect; // Set by manual scrolling, if we scroll to a point where NavId isn't visible we reset navigation from visible items bool NavMoveRequest; // Move request for this frame ImGuiNavForward NavMoveRequestForward; // None / ForwardQueued / ForwardActive (this is used to navigate sibling parent menus from a child menu) ImGuiDir NavMoveDir, NavMoveDirLast; // Direction of the move request (left/right/up/down), direction of the previous move request ImGuiNavMoveResult NavMoveResultLocal; // Best move request candidate within NavWindow ImGuiNavMoveResult NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using the NavFlattened flag) // Render ImDrawData DrawData; // Main ImDrawData instance to pass render information to the user ImDrawDataBuilder DrawDataBuilder; float ModalWindowDarkeningRatio; ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays ImGuiMouseCursor MouseCursor; // Drag and Drop bool DragDropActive; ImGuiDragDropFlags DragDropSourceFlags; int DragDropMouseButton; ImGuiPayload DragDropPayload; ImRect DragDropTargetRect; ImGuiID DragDropTargetId; float DragDropAcceptIdCurrRectSurface; ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload) ImGuiID DragDropAcceptIdPrev; // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets) int DragDropAcceptFrameCount; // Last time a target expressed a desire to accept the source ImVector DragDropPayloadBufHeap; // We don't expose the ImVector<> directly unsigned char DragDropPayloadBufLocal[8]; // Widget state ImGuiTextEditState InputTextState; ImFont InputTextPasswordFont; ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets ImVec4 ColorPickerRef; 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? int TooltipOverrideCount; ImVector PrivateClipboard; // If no custom clipboard handler is defined ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor // Settings float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero ImVector SettingsWindows; // .ini settings for ImGuiWindow ImVector SettingsHandlers; // List of .ini settings handlers // 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 WantCaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags int WantCaptureKeyboardNextFrame; int WantTextInputNextFrame; char TempBuffer[1024*3+1]; // temporary text buffer ImGuiContext(ImFontAtlas* shared_font_atlas) : OverlayDrawList(NULL) { Initialized = false; Font = NULL; FontSize = FontBaseSize = 0.0f; FontAtlasOwnedByContext = shared_font_atlas ? false : true; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); Time = 0.0f; FrameCount = 0; FrameCountEnded = FrameCountRendered = -1; WindowsActiveCount = 0; CurrentWindow = NULL; HoveredWindow = NULL; HoveredRootWindow = NULL; HoveredId = 0; HoveredIdAllowOverlap = false; HoveredIdPreviousFrame = 0; HoveredIdTimer = 0.0f; ActiveId = 0; ActiveIdPreviousFrame = 0; ActiveIdTimer = 0.0f; ActiveIdIsAlive = false; ActiveIdIsJustActivated = false; ActiveIdAllowOverlap = false; ActiveIdAllowNavDirFlags = 0; ActiveIdClickOffset = ImVec2(-1,-1); ActiveIdWindow = NULL; ActiveIdSource = ImGuiInputSource_None; MovingWindow = NULL; NextTreeNodeOpenVal = false; NextTreeNodeOpenCond = 0; NavWindow = NULL; NavId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0; NavJustTabbedId = NavJustMovedToId = NavNextActivateId = 0; NavScoringRectScreen = ImRect(); NavScoringCount = 0; NavWindowingTarget = NULL; NavWindowingHighlightTimer = NavWindowingHighlightAlpha = 0.0f; NavWindowingToggleLayer = false; NavWindowingInputSource = ImGuiInputSource_None; NavLayer = 0; NavIdTabCounter = INT_MAX; NavIdIsAlive = false; NavMousePosDirty = false; NavDisableHighlight = true; NavDisableMouseHover = false; NavAnyRequest = false; NavInitRequest = false; NavInitRequestFromMove = false; NavInitResultId = 0; NavMoveFromClampedRefRect = false; NavMoveRequest = false; NavMoveRequestForward = ImGuiNavForward_None; NavMoveDir = NavMoveDirLast = ImGuiDir_None; ModalWindowDarkeningRatio = 0.0f; OverlayDrawList._Data = &DrawListSharedData; OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging MouseCursor = ImGuiMouseCursor_Arrow; DragDropActive = false; DragDropSourceFlags = 0; DragDropMouseButton = -1; DragDropTargetId = 0; DragDropAcceptIdCurrRectSurface = 0.0f; DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0; DragDropAcceptFrameCount = -1; memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal)); ScalarAsInputTextId = 0; ColorEditOptions = ImGuiColorEditFlags__OptionsDefault; DragCurrentValue = 0.0f; DragLastMouseDelta = ImVec2(0.0f, 0.0f); DragSpeedDefaultRatio = 1.0f / 100.0f; DragSpeedScaleSlow = 1.0f / 100.0f; DragSpeedScaleFast = 10.0f; ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f); TooltipOverrideCount = 0; OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f); SettingsDirtyTimer = 0.0f; LogEnabled = false; LogFile = NULL; LogClipboard = NULL; LogStartDepth = 0; LogAutoExpandMaxDepth = 2; memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); FramerateSecPerFrameIdx = 0; FramerateSecPerFrameAccum = 0.0f; WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1; memset(TempBuffer, 0, sizeof(TempBuffer)); } }; // Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin(). // This is going to be exposed in imgui.h when stabilized enough. enum ImGuiItemFlags_ { ImGuiItemFlags_AllowKeyboardFocus = 1 << 0, // true ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. ImGuiItemFlags_Disabled = 1 << 2, // false // FIXME-WIP: Disable interactions but doesn't affect visuals. Should be: grey out and disable interactions with widgets that affect data + view widgets (WIP) ImGuiItemFlags_NoNav = 1 << 3, // false ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window ImGuiItemFlags_Default_ = ImGuiItemFlags_AllowKeyboardFocus }; // 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; // Used to implicitly calculate the size of our contents, always growing during the frame. Turned into window->SizeContents at the beginning of next frame float CurrentLineHeight; float CurrentLineTextBaseOffset; float PrevLineHeight; float PrevLineTextBaseOffset; float LogLinePosY; int TreeDepth; ImU32 TreeDepthMayCloseOnPop; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31 ImGuiID LastItemId; ImGuiItemStatusFlags LastItemStatusFlags; ImRect LastItemRect; // Interaction rect ImRect LastItemDisplayRect; // End-user display rect (only valid if LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) bool NavHideHighlightOneFrame; bool NavHasScroll; // Set when scrolling can be used (ScrollMax > 0.0f) int NavLayerCurrent; // Current layer, 0..31 (we currently only use 0..1) int NavLayerCurrentMask; // = (1 << NavLayerCurrent) used by ItemAdd prior to clipping. int NavLayerActiveMask; // Which layer have been written to (result from previous frame) int NavLayerActiveMaskNext; // Which layer have been written to (buffer for current frame) bool MenuBarAppending; // FIXME: Remove this float MenuBarOffsetX; ImVector ChildWindows; ImGuiStorage* StateStorage; ImGuiLayoutType LayoutType; ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() // 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. ImGuiItemFlags ItemFlags; // == ItemFlagsStack.back() [empty == ImGuiItemFlags_Default] 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] ImVectorItemFlagsStack; ImVector ItemWidthStack; ImVector TextWrapPosStack; ImVectorGroupStack; 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. ImGuiColumnsSet* ColumnsSet; // Current columns set ImGuiDrawContext() { CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); CurrentLineHeight = PrevLineHeight = 0.0f; CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; LogLinePosY = -1.0f; TreeDepth = 0; TreeDepthMayCloseOnPop = 0x00; LastItemId = 0; LastItemStatusFlags = 0; LastItemRect = LastItemDisplayRect = ImRect(); NavHideHighlightOneFrame = false; NavHasScroll = false; NavLayerActiveMask = NavLayerActiveMaskNext = 0x00; NavLayerCurrent = 0; NavLayerCurrentMask = 1 << 0; MenuBarAppending = false; MenuBarOffsetX = 0.0f; StateStorage = NULL; LayoutType = ParentLayoutType = ImGuiLayoutType_Vertical; ItemWidth = 0.0f; ItemFlags = ImGuiItemFlags_Default_; TextWrapPos = -1.0f; memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); IndentX = 0.0f; GroupOffsetX = 0.0f; ColumnsOffsetX = 0.0f; ColumnsSet = NULL; } }; // Windows data struct IMGUI_API ImGuiWindow { char* Name; ImGuiID ID; // == ImHash(Name) ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_ 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 SizeFullAtLastBegin; // Copy of SizeFull at the end of Begin. This is the reference value we'll use on the next frame to decide if we need scrollbars. ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame. Include decoration, window title, border, menu, etc. 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. float WindowRounding; // Window rounding at the time of begin. float WindowBorderSize; // Window border size at the time of begin. ImGuiID MoveId; // == window->GetID("#MOVE") ImGuiID ChildId; // Id of corresponding item in parent window (for child windows) 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; bool Active; // Set to true on Begin(), unless Collapsed bool WasActive; bool WriteAccessed; // Set to true when any widget access the current window bool Collapsed; // Set when collapsing window to become only title-bar bool CollapseToggleWanted; bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed) bool Appearing; // Set during the frame where the window is appearing (or re-appearing) bool CloseButton; // Set when the window has a close button (p_open != NULL) int BeginOrderWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0. int BeginOrderWithinContext; // Order within entire imgui context. This is mostly used for debugging submission order related issues. 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 AutoFitChildAxises; ImGuiDir AutoPosLastDirection; int HiddenFrames; ImGuiCond SetWindowPosAllowFlags; // store condition flags for next SetWindowPos() call. ImGuiCond SetWindowSizeAllowFlags; // store condition flags for next SetWindowSize() call. ImGuiCond SetWindowCollapsedAllowFlags; // store condition flags for next SetWindowCollapsed() call. ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0,0) when positioning from top-left corner; ImVec2(0.5f,0.5f) for centering; ImVec2(1,1) for bottom right. ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame ImVector 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. ImRect InnerRect; int LastFrameActive; float ItemWidthDefault; ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items ImGuiStorage StateStorage; ImVector ColumnsStorage; float FontWindowScale; // Scale multiplier per-window ImDrawList* DrawList; ImGuiWindow* ParentWindow; // If we are a child _or_ popup window, this is pointing to our parent. Otherwise NULL. ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window. ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active. ImGuiWindow* RootWindowForTabbing; // Point to ourself or first ancestor which can be CTRL-Tabbed into. ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag. ImGuiWindow* NavLastChildNavWindow; // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) ImGuiID NavLastIds[2]; // Last known NavId for this window, per layer (0/1) ImRect NavRectRel[2]; // Reference rectangle, in window relative space // Navigation / Focus // FIXME-NAV: Merge all this with the new Nav system, at least the request variables should be moved to ImGuiContext 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(ImGuiContext* context, 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); ImGuiID GetIDFromRectangle(const ImRect& r_abs); // We don't use g.FontSize because the window may be != g.CurrentWidow. 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()); } }; // Backup and restore just enough data to be able to use IsItemHovered() on item A after another B in the same window has overwritten the data. struct ImGuiItemHoveredDataBackup { ImGuiID LastItemId; ImGuiItemStatusFlags LastItemStatusFlags; ImRect LastItemRect; ImRect LastItemDisplayRect; ImGuiItemHoveredDataBackup() { Backup(); } void Backup() { ImGuiWindow* window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemStatusFlags = window->DC.LastItemStatusFlags; LastItemRect = window->DC.LastItemRect; LastItemDisplayRect = window->DC.LastItemDisplayRect; } void Restore() const { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.LastItemId = LastItemId; window->DC.LastItemStatusFlags = LastItemStatusFlags; window->DC.LastItemRect = LastItemRect; window->DC.LastItemDisplayRect = LastItemDisplayRect; } }; //----------------------------------------------------------------------------- // 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->WriteAccessed = true; return g.CurrentWindow; } IMGUI_API ImGuiWindow* FindWindowByName(const char* name); IMGUI_API void FocusWindow(ImGuiWindow* window); IMGUI_API void BringWindowToFront(ImGuiWindow* window); IMGUI_API void BringWindowToBack(ImGuiWindow* window); IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent); IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); IMGUI_API void Initialize(ImGuiContext* context); IMGUI_API void Shutdown(ImGuiContext* context); // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext(). IMGUI_API void MarkIniSettingsDirty(); IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name); IMGUI_API ImGuiWindowSettings* FindWindowSettings(ImGuiID id); IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); IMGUI_API ImGuiID GetActiveID(); IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window); IMGUI_API void ClearActiveID(); IMGUI_API void SetHoveredID(ImGuiID id); IMGUI_API ImGuiID GetHoveredID(); 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, ImGuiID id, const ImRect* nav_bb = NULL); IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id); IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged); IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id, 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 PushMultiItemsWidths(int components, float width_full = 0.0f); IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); IMGUI_API void PopItemFlag(); IMGUI_API void SetCurrentFont(ImFont* font); IMGUI_API void OpenPopupEx(ImGuiID id); IMGUI_API void ClosePopup(ImGuiID id); IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window); IMGUI_API bool IsPopupOpen(ImGuiID id); IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip = true); IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit); IMGUI_API void ActivateItem(ImGuiID id); // Remotely activate a button, checkbox, tree node etc. given its unique ID. activation is queued and processed on the next frame when the item is encountered again. IMGUI_API float GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode); IMGUI_API ImVec2 GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor = 0.0f, float fast_factor = 0.0f); IMGUI_API int CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate); IMGUI_API void Scrollbar(ImGuiLayoutType direction); IMGUI_API void VerticalSeparator(); // Vertical separator, for menu bars (use current line height). not exposed because it is misleading what it doesn't have an effect on regular layout. IMGUI_API bool SplitterBehavior(ImGuiID id, const ImRect& bb, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f); IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id); IMGUI_API void ClearDragDrop(); IMGUI_API bool IsDragDropPayloadBeingAccepted(); // FIXME-WIP: New Columns API IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiColumnsFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). IMGUI_API void EndColumns(); // close columns IMGUI_API void PushColumnClipRect(int column_index = -1); // NB: All position are in absolute pixels coordinates (never using window coordinates internally) // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT. 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 RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f); IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, int rounding_corners_flags = ~0); IMGUI_API void RenderTriangle(ImVec2 pos, ImGuiDir dir, float scale = 1.0f); IMGUI_API void RenderBullet(ImVec2 pos); IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col, float sz); IMGUI_API void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_TypeDefault); // Navigation highlight IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding); 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 ArrowButton(ImGuiID id, ImGuiDir dir, ImVec2 padding, ImGuiButtonFlags flags = 0); 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 void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags); IMGUI_API void ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags); 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); // Shade functions IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawVert* vert_start, ImDrawVert* vert_end, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1); IMGUI_API void ShadeVertsLinearAlphaGradientForLeftToRightText(ImDrawVert* vert_start, ImDrawVert* vert_end, float gradient_p0_x, float gradient_p1_x); IMGUI_API void ShadeVertsLinearUV(ImDrawVert* vert_start, ImDrawVert* vert_end, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp); } // namespace ImGui // ImFontAtlas internals IMGUI_API bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent); IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* spc); IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor); IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride); #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef _MSC_VER #pragma warning (pop) #endif ================================================ FILE: ui/imgui/stb_rect_pack.h ================================================ // stb_rect_pack.h - v0.11 - public domain - rectangle packing // Sean Barrett 2014 // // Useful for e.g. packing rectangular textures into an atlas. // Does not do rotation. // // Not necessarily the awesomest packing method, but better than // the totally naive one in stb_truetype (which is primarily what // this is meant to replace). // // Has only had a few tests run, may have issues. // // 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. // // Please note: better rectangle packers are welcome! Please // implement them to the same API, but with a different init // function. // // Credits // // Library // Sean Barrett // Minor features // Martins Mozeiko // github:IntellectualKitty // // Bugfixes / warning fixes // Jeremy Jaussaud // // Version history: // // 0.11 (2017-03-03) return packing success/fail result // 0.10 (2016-10-25) remove cast-away-const to avoid warnings // 0.09 (2016-08-27) fix compiler warnings // 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 // // See end of file for license information. ////////////////////////////////////////////////////////////////////////////// // // INCLUDE SECTION // #ifndef STB_INCLUDE_STB_RECT_PACK_H #define STB_INCLUDE_STB_RECT_PACK_H #define STB_RECT_PACK_VERSION 1 #ifdef STBRP_STATIC #define STBRP_DEF static #else #define STBRP_DEF extern #endif #ifdef __cplusplus extern "C" { #endif typedef struct stbrp_context stbrp_context; typedef struct stbrp_node stbrp_node; typedef struct stbrp_rect stbrp_rect; #ifdef STBRP_LARGE_RECTS typedef int stbrp_coord; #else typedef unsigned short stbrp_coord; #endif STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects); // Assign packed locations to rectangles. The rectangles are of type // 'stbrp_rect' defined below, stored in the array 'rects', and there // are 'num_rects' many of them. // // Rectangles which are successfully packed have the 'was_packed' flag // set to a non-zero value and 'x' and 'y' store the minimum location // on each axis (i.e. bottom-left in cartesian coordinates, top-left // if you imagine y increasing downwards). Rectangles which do not fit // have the 'was_packed' flag set to 0. // // You should not try to access the 'rects' array from another thread // while this function is running, as the function temporarily reorders // the array while it executes. // // To pack into another rectangle, you need to call stbrp_init_target // again. To continue packing into the same rectangle, you can call // this function again. Calling this multiple times with multiple rect // arrays will probably produce worse packing results than calling it // a single time with the full rectangle array, but the option is // available. // // The function returns 1 if all of the rectangles were successfully // packed and 0 otherwise. struct stbrp_rect { // reserved for your use: int id; // input: stbrp_coord w, h; // output: stbrp_coord x, y; int was_packed; // non-zero if valid packing }; // 16 bytes, nominally STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes); // Initialize a rectangle packer to: // pack a rectangle that is 'width' by 'height' in dimensions // using temporary storage provided by the array 'nodes', which is 'num_nodes' long // // You must call this function every time you start packing into a new target. // // There is no "shutdown" function. The 'nodes' memory must stay valid for // the following stbrp_pack_rects() call (or calls), but can be freed after // the call (or calls) finish. // // Note: to guarantee best results, either: // 1. make sure 'num_nodes' >= 'width' // or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1' // // If you don't do either of the above things, widths will be quantized to multiples // of small integers to guarantee the algorithm doesn't run out of temporary storage. // // If you do #2, then the non-quantized algorithm will be used, but the algorithm // may run out of temporary storage and be unable to pack some rectangles. STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem); // Optionally call this function after init but before doing any packing to // change the handling of the out-of-temp-memory scenario, described above. // If you call init again, this will be reset to the default (false). STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic); // Optionally select which packing heuristic the library should use. Different // heuristics will produce better/worse results for different data sets. // If you call init again, this will be reset to the default. enum { STBRP_HEURISTIC_Skyline_default=0, STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default, STBRP_HEURISTIC_Skyline_BF_sortHeight }; ////////////////////////////////////////////////////////////////////////////// // // the details of the following structures don't matter to you, but they must // be visible so you can handle the memory allocations for them struct stbrp_node { stbrp_coord x,y; stbrp_node *next; }; struct stbrp_context { int width; int height; int align; int init_mode; int heuristic; int num_nodes; stbrp_node *active_head; stbrp_node *free_head; stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' }; #ifdef __cplusplus } #endif #endif ////////////////////////////////////////////////////////////////////////////// // // IMPLEMENTATION SECTION // #ifdef STB_RECT_PACK_IMPLEMENTATION #ifndef STBRP_SORT #include #define STBRP_SORT qsort #endif #ifndef STBRP_ASSERT #include #define STBRP_ASSERT assert #endif #ifdef _MSC_VER #define STBRP__NOTUSED(v) (void)(v) #define STBRP__CDECL __cdecl #else #define STBRP__NOTUSED(v) (void)sizeof(v) #define STBRP__CDECL #endif enum { STBRP__INIT_skyline = 1 }; STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic) { switch (context->init_mode) { case STBRP__INIT_skyline: STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight); context->heuristic = heuristic; break; default: STBRP_ASSERT(0); } } STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem) { if (allow_out_of_mem) // if it's ok to run out of memory, then don't bother aligning them; // this gives better packing, but may fail due to OOM (even though // the rectangles easily fit). @TODO a smarter approach would be to only // quantize once we've hit OOM, then we could get rid of this parameter. context->align = 1; else { // if it's not ok to run out of memory, then quantize the widths // so that num_nodes is always enough nodes. // // I.e. num_nodes * align >= width // align >= width / num_nodes // align = ceil(width/num_nodes) context->align = (context->width + context->num_nodes-1) / context->num_nodes; } } STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes) { int i; #ifndef STBRP_LARGE_RECTS STBRP_ASSERT(width <= 0xffff && height <= 0xffff); #endif for (i=0; i < num_nodes-1; ++i) nodes[i].next = &nodes[i+1]; nodes[i].next = NULL; context->init_mode = STBRP__INIT_skyline; context->heuristic = STBRP_HEURISTIC_Skyline_default; context->free_head = &nodes[0]; context->active_head = &context->extra[0]; context->width = width; context->height = height; context->num_nodes = num_nodes; stbrp_setup_allow_out_of_mem(context, 0); // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) context->extra[0].x = 0; context->extra[0].y = 0; context->extra[0].next = &context->extra[1]; context->extra[1].x = (stbrp_coord) width; #ifdef STBRP_LARGE_RECTS context->extra[1].y = (1<<30); #else context->extra[1].y = 65535; #endif context->extra[1].next = NULL; } // 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) { stbrp_node *node = first; int x1 = x0 + width; int min_y, visited_width, waste_area; STBRP__NOTUSED(c); STBRP_ASSERT(first->x <= x0); #if 0 // skip in case we're past the node while (node->next->x <= x0) ++node; #else STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency #endif STBRP_ASSERT(node->x <= x0); min_y = 0; waste_area = 0; visited_width = 0; while (node->x < x1) { if (node->y > min_y) { // raise min_y higher. // we've accounted for all waste up to min_y, // but we'll now add more waste for everything we've visted waste_area += visited_width * (node->y - min_y); min_y = node->y; // the first time through, visited_width might be reduced if (node->x < x0) visited_width += node->next->x - x0; else visited_width += node->next->x - node->x; } else { // add waste area int under_width = node->next->x - node->x; if (under_width + visited_width > width) under_width = width - visited_width; waste_area += under_width * (min_y - node->y); visited_width += under_width; } node = node->next; } *pwaste = waste_area; return min_y; } typedef struct { int x,y; stbrp_node **prev_link; } stbrp__findresult; static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height) { int best_waste = (1<<30), best_x, best_y = (1 << 30); stbrp__findresult fr; stbrp_node **prev, *node, *tail, **best = NULL; // align to multiple of c->align width = (width + c->align - 1); width -= width % c->align; STBRP_ASSERT(width % c->align == 0); node = c->active_head; prev = &c->active_head; while (node->x + width <= c->width) { int y,waste; y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste); if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL // bottom left if (y < best_y) { best_y = y; best = prev; } } else { // best-fit if (y + height <= c->height) { // can only use it if it first vertically if (y < best_y || (y == best_y && waste < best_waste)) { best_y = y; best_waste = waste; best = prev; } } } prev = &node->next; node = node->next; } best_x = (best == NULL) ? 0 : (*best)->x; // if doing best-fit (BF), we also have to try aligning right edge to each node position // // e.g, if fitting // // ____________________ // |____________________| // // into // // | | // | ____________| // |____________| // // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned // // This makes BF take about 2x the time if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) { tail = c->active_head; node = c->active_head; prev = &c->active_head; // find first node that's admissible while (tail->x < width) tail = tail->next; while (tail) { int xpos = tail->x - width; int y,waste; STBRP_ASSERT(xpos >= 0); // find the left position that matches this while (node->next->x <= xpos) { prev = &node->next; node = node->next; } STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); if (y + height < c->height) { if (y <= best_y) { if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { best_x = xpos; STBRP_ASSERT(y <= best_y); best_y = y; best_waste = waste; best = prev; } } } tail = tail->next; } } fr.prev_link = best; fr.x = best_x; fr.y = best_y; return fr; } static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height) { // find best position according to heuristic stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height); stbrp_node *node, *cur; // bail if: // 1. it failed // 2. the best node doesn't fit (we don't always check this) // 3. we're out of memory if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) { res.prev_link = NULL; return res; } // on success, create new node node = context->free_head; node->x = (stbrp_coord) res.x; node->y = (stbrp_coord) (res.y + height); context->free_head = node->next; // insert the new node into the right starting point, and // let 'cur' point to the remaining nodes needing to be // stiched back in cur = *res.prev_link; if (cur->x < res.x) { // preserve the existing one, so start testing with the next one stbrp_node *next = cur->next; cur->next = node; cur = next; } else { *res.prev_link = node; } // from here, traverse cur and free the nodes, until we get to one // that shouldn't be freed while (cur->next && cur->next->x <= res.x + width) { stbrp_node *next = cur->next; // move the current node to the free list cur->next = context->free_head; context->free_head = cur; cur = next; } // stitch the list back in node->next = cur; if (cur->x < res.x + width) cur->x = (stbrp_coord) (res.x + width); #ifdef _DEBUG cur = context->active_head; while (cur->x < context->width) { STBRP_ASSERT(cur->x < cur->next->x); cur = cur->next; } STBRP_ASSERT(cur->next == NULL); { int count=0; cur = context->active_head; while (cur) { cur = cur->next; ++count; } cur = context->free_head; while (cur) { cur = cur->next; ++count; } STBRP_ASSERT(count == context->num_nodes+2); } #endif return res; } static int STBRP__CDECL rect_height_compare(const void *a, const void *b) { const stbrp_rect *p = (const stbrp_rect *) a; const stbrp_rect *q = (const stbrp_rect *) b; if (p->h > q->h) return -1; if (p->h < q->h) return 1; return (p->w > q->w) ? -1 : (p->w < q->w); } static int STBRP__CDECL rect_original_order(const void *a, const void *b) { const stbrp_rect *p = (const stbrp_rect *) a; const stbrp_rect *q = (const stbrp_rect *) b; return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); } #ifdef STBRP_LARGE_RECTS #define STBRP__MAXVAL 0xffffffff #else #define STBRP__MAXVAL 0xffff #endif STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects) { int i, all_rects_packed = 1; // we use the 'was_packed' field internally to allow sorting/unsorting for (i=0; i < num_rects; ++i) { rects[i].was_packed = i; #ifndef STBRP_LARGE_RECTS STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff); #endif } // sort according to heuristic STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); for (i=0; i < num_rects; ++i) { if (rects[i].w == 0 || rects[i].h == 0) { rects[i].x = rects[i].y = 0; // empty rect needs no space } else { 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 STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); // set was_packed flags and all_rects_packed status for (i=0; i < num_rects; ++i) { rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL); if (!rects[i].was_packed) all_rects_packed = 0; } // return the all_rects_packed status return all_rects_packed; } #endif /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */ ================================================ FILE: ui/imgui/stb_textedit.h ================================================ // [ImGui] this is a slightly modified version of stb_truetype.h 1.9. Those changes would need to be pushed into nothings/sb // [ImGui] - fixed linestart handler when over last character of multi-line buffer + simplified existing code (#588, #815) // [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 // stb_textedit.h - v1.9 - 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 // widget; you implement display, word-wrapping, and low-level string // insertion/deletion, and stb_textedit will map user inputs into // insertions & deletions, plus updates to the cursor position, // selection state, and undo state. // // It is intended for use in games and other systems that need to build // their own custom widgets and which do not have heavy text-editing // requirements (this library is not recommended for use for editing large // texts, as its performance does not scale and it has limited undo). // // Non-trivial behaviors are modelled after Windows text controls. // // // LICENSE // // 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', which you can override // by defining STB_TEXTEDIT_memmove before the implementation. // Uses no other functions. Performs no runtime allocations. // // // VERSION HISTORY // // 1.9 (2016-08-27) customizable move-by-word // 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 // 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) // 1.0 (2012-07-26) improve documentation, initial public release // 0.3 (2012-02-24) bugfixes, single-line mode; insert mode // 0.2 (2011-11-28) fixes to undo/redo // 0.1 (2010-07-08) initial version // // ADDITIONAL CONTRIBUTORS // // Ulf Winklemann: move-by-word in 1.1 // Fabian Giesen: secondary key inputs in 1.5 // Martins Mozeiko: STB_TEXTEDIT_memmove // // Bugfixes: // Scott Graham // Daniel Keller // Omar Cornut // // USAGE // // This file behaves differently depending on what symbols you define // before including it. // // // Header-file mode: // // If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this, // it will operate in "header file" mode. In this mode, it declares a // single public symbol, STB_TexteditState, which encapsulates the current // state of a text widget (except for the string, which you will store // separately). // // To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a // primitive type that defines a single character (e.g. char, wchar_t, etc). // // To save space or increase undo-ability, you can optionally define the // following things that are used by the undo system: // // STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position // STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow // STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer // // If you don't define these, they are set to permissive types and // moderate sizes. The undo system does no memory allocations, so // it grows STB_TexteditState by the worst-case storage which is (in bytes): // // [4 + sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT // + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHAR_COUNT // // // Implementation mode: // // If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it // will compile the implementation of the text edit widget, depending // on a large number of symbols which must be defined before the include. // // The implementation is defined only as static functions. You will then // need to provide your own APIs in the same file which will access the // static functions. // // The basic concept is that you provide a "string" object which // behaves like an array of characters. stb_textedit uses indices to // refer to positions in the string, implicitly representing positions // in the displayed textedit. This is true for both plain text and // rich text; even with rich text stb_truetype interacts with your // code as if there was an array of all the displayed characters. // // Symbols that must be the same in header-file and implementation mode: // // STB_TEXTEDIT_CHARTYPE the character type // STB_TEXTEDIT_POSITIONTYPE small type that a valid cursor position // STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow // STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer // // Symbols you must define for implementation mode: // // STB_TEXTEDIT_STRING the type of object representing a string being edited, // typically this is a wrapper object with other data you need // // STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) // STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters // starting from character #n (see discussion below) // STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character // to the xpos of the i+1'th char for a line of characters // starting at character #n (i.e. accounts for kerning // with previous char) // STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character // (return type is int, -1 means not valid to insert) // STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based // STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize // as manually wordwrapping for end-of-line positioning // // STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i // STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) // // STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key // // STB_TEXTEDIT_K_LEFT keyboard input to move cursor left // STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right // STB_TEXTEDIT_K_UP keyboard input to move cursor up // STB_TEXTEDIT_K_DOWN keyboard input to move cursor down // STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME // STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END // STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME // STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END // STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor // STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor // STB_TEXTEDIT_K_UNDO keyboard input to perform undo // 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 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 // STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page // // Keyboard input must be encoded as a single integer value; e.g. a character code // and some bitflags that represent shift states. to simplify the interface, SHIFT must // be a bitflag, so we can test the shifted state of cursor movements to allow selection, // i.e. (STB_TEXTED_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. // // You can encode other things, such as CONTROL or ALT, in additional bits, and // then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, // my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN // bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit, // and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the // API below. The control keys will only match WM_KEYDOWN events because of the // keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN // bit so it only decodes WM_CHAR events. // // STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed // row of characters assuming they start on the i'th character--the width and // the height and the number of characters consumed. This allows this library // to traverse the entire layout incrementally. You need to compute word-wrapping // here. // // Each textfield keeps its own insert mode state, which is not how normal // applications work. To keep an app-wide insert mode, update/copy the // "insert_mode" field of STB_TexteditState before/after calling API functions. // // API // // void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) // // void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) // void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) // int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) // int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) // void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int key) // // Each of these functions potentially updates the string and updates the // state. // // initialize_state: // set the textedit state to a known good default state when initially // constructing the textedit. // // click: // call this with the mouse x,y on a mouse down; it will update the cursor // and reset the selection start/end to the cursor point. the x,y must // be relative to the text widget, with (0,0) being the top left. // // drag: // call this with the mouse x,y on a mouse drag/up; it will update the // cursor and the selection end point // // cut: // call this to delete the current selection; returns true if there was // one. you should FIRST copy the current selection to the system paste buffer. // (To copy, just copy the current selection out of the string yourself.) // // paste: // call this to paste text at the current cursor point or over the current // selection if there is one. // // key: // call this for keyboard inputs sent to the textfield. you can use it // for "key down" events or for "translated" key events. if you need to // do both (as in Win32), or distinguish Unicode characters from control // inputs, set a high bit to distinguish the two; then you can define the // various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit // set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is // clear. // // When rendering, you can read the cursor position and selection state from // the STB_TexteditState. // // // Notes: // // This is designed to be usable in IMGUI, so it allows for the possibility of // running in an IMGUI that has NOT cached the multi-line layout. For this // reason, it provides an interface that is compatible with computing the // layout incrementally--we try to make sure we make as few passes through // as possible. (For example, to locate the mouse pointer in the text, we // could define functions that return the X and Y positions of characters // and binary search Y and then X, but if we're doing dynamic layout this // will run the layout algorithm many times, so instead we manually search // forward in one pass. Similar logic applies to e.g. up-arrow and // down-arrow movement.) // // If it's run in a widget that *has* cached the layout, then this is less // efficient, but it's not horrible on modern computers. But you wouldn't // want to edit million-line files with it. //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //// //// Header-file mode //// //// #ifndef INCLUDE_STB_TEXTEDIT_H #define INCLUDE_STB_TEXTEDIT_H //////////////////////////////////////////////////////////////////////// // // STB_TexteditState // // Definition of STB_TexteditState which you should store // per-textfield; it includes cursor position, selection state, // and undo state. // #ifndef STB_TEXTEDIT_UNDOSTATECOUNT #define STB_TEXTEDIT_UNDOSTATECOUNT 99 #endif #ifndef STB_TEXTEDIT_UNDOCHARCOUNT #define STB_TEXTEDIT_UNDOCHARCOUNT 999 #endif #ifndef STB_TEXTEDIT_CHARTYPE #define STB_TEXTEDIT_CHARTYPE int #endif #ifndef STB_TEXTEDIT_POSITIONTYPE #define STB_TEXTEDIT_POSITIONTYPE int #endif typedef struct { // private data STB_TEXTEDIT_POSITIONTYPE where; short insert_length; short delete_length; short char_storage; } StbUndoRecord; typedef struct { // private data StbUndoRecord undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT]; STB_TEXTEDIT_CHARTYPE undo_char[STB_TEXTEDIT_UNDOCHARCOUNT]; short undo_point, redo_point; short undo_char_point, redo_char_point; } StbUndoState; typedef struct { ///////////////////// // // public data // int cursor; // position of the text cursor within the string int select_start; // selection start point int select_end; // selection start and end point in characters; if equal, no selection. // note that start may be less than or greater than end (e.g. when // dragging the mouse, start is where the initial click was, and you // can drag in either direction) unsigned char insert_mode; // each textfield keeps its own insert mode state. to keep an app-wide // insert mode, copy this value in/out of the app state ///////////////////// // // private data // unsigned char cursor_at_end_of_line; // not implemented yet unsigned char initialized; unsigned char has_preferred_x; unsigned char single_line; unsigned char padding1, padding2, padding3; float preferred_x; // this determines where the cursor up/down tries to seek to along x StbUndoState undostate; } STB_TexteditState; //////////////////////////////////////////////////////////////////////// // // StbTexteditRow // // Result of layout query, used by stb_textedit to determine where // the text in each row is. // result of layout query typedef struct { float x0,x1; // starting x location, end x location (allows for align=right, etc) float baseline_y_delta; // position of baseline relative to previous row's baseline float ymin,ymax; // height of row above and below baseline int num_chars; } StbTexteditRow; #endif //INCLUDE_STB_TEXTEDIT_H //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //// //// Implementation mode //// //// // implementation isn't include-guarded, since it might have indirectly // included just the "header" portion #ifdef STB_TEXTEDIT_IMPLEMENTATION #ifndef STB_TEXTEDIT_memmove #include #define STB_TEXTEDIT_memmove memmove #endif ///////////////////////////////////////////////////////////////////////////// // // Mouse input handling // // traverse the layout to locate the nearest character to a display position static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) { StbTexteditRow r; int n = STB_TEXTEDIT_STRINGLEN(str); float base_y = 0, prev_x; int i=0, k; r.x0 = r.x1 = 0; r.ymin = r.ymax = 0; r.num_chars = 0; // search rows to find one that straddles 'y' while (i < n) { STB_TEXTEDIT_LAYOUTROW(&r, str, i); if (r.num_chars <= 0) return n; if (i==0 && y < base_y + r.ymin) return 0; if (y < base_y + r.ymax) break; i += r.num_chars; base_y += r.baseline_y_delta; } // below all text, return 'after' last character if (i >= n) return n; // check if it's before the beginning of the line if (x < r.x0) return i; // check if it's before the end of the line if (x < r.x1) { // search characters in row for one that straddles 'x' prev_x = r.x0; for (k=0; k < r.num_chars; ++k) { float w = STB_TEXTEDIT_GETWIDTH(str, i, k); if (x < prev_x+w) { if (x < prev_x+w/2) return k+i; else return k+i+1; } prev_x += w; } // shouldn't happen, but if it does, fall through to end-of-line case } // if the last character is a newline, return that. otherwise return 'after' the last character if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE) return i+r.num_chars-1; else return i+r.num_chars; } // API click: on mouse down, move the cursor to the clicked location, and reset the selection static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) { state->cursor = stb_text_locate_coord(str, x, y); state->select_start = state->cursor; state->select_end = state->cursor; state->has_preferred_x = 0; } // API drag: on mouse drag, move the cursor and selection endpoint to the clicked location 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; } ///////////////////////////////////////////////////////////////////////////// // // Keyboard input handling // // forward declarations static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length); static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length); static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length); typedef struct { float x,y; // position of n'th character float height; // height of line int first_char, length; // first char of row, and length int prev_first; // first char of previous row } StbFindState; // find the x/y location of a character, and remember info about the previous row in // case we get a move-up event (for page up, we'll have to rescan) static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line) { StbTexteditRow r; int prev_start = 0; int z = STB_TEXTEDIT_STRINGLEN(str); int i=0, first; if (n == z) { // if it's at the end, then find the last line -- simpler than trying to // explicitly handle this case in the regular code if (single_line) { STB_TEXTEDIT_LAYOUTROW(&r, str, 0); find->y = 0; find->first_char = 0; find->length = z; find->height = r.ymax - r.ymin; find->x = r.x1; } else { find->y = 0; find->x = 0; find->height = 1; while (i < z) { STB_TEXTEDIT_LAYOUTROW(&r, str, i); prev_start = i; i += r.num_chars; } find->first_char = i; find->length = 0; find->prev_first = prev_start; } return; } // search rows to find the one that straddles character n find->y = 0; for(;;) { STB_TEXTEDIT_LAYOUTROW(&r, str, i); if (n < i + r.num_chars) break; prev_start = i; i += r.num_chars; find->y += r.baseline_y_delta; } find->first_char = first = i; find->length = r.num_chars; find->height = r.ymax - r.ymin; find->prev_first = prev_start; // now scan to find xpos find->x = r.x0; i = 0; for (i=0; first+i < n; ++i) find->x += STB_TEXTEDIT_GETWIDTH(str, first, i); } #define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) // make the selection/cursor state valid if client altered the string static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) { int n = STB_TEXTEDIT_STRINGLEN(str); if (STB_TEXT_HAS_SELECTION(state)) { if (state->select_start > n) state->select_start = n; if (state->select_end > n) state->select_end = n; // if clamping forced them to be equal, move the cursor to match if (state->select_start == state->select_end) state->cursor = state->select_start; } if (state->cursor > n) state->cursor = n; } // delete characters while updating undo static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len) { stb_text_makeundo_delete(str, state, where, len); STB_TEXTEDIT_DELETECHARS(str, where, len); state->has_preferred_x = 0; } // delete the section static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) { stb_textedit_clamp(str, state); if (STB_TEXT_HAS_SELECTION(state)) { if (state->select_start < state->select_end) { stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start); state->select_end = state->cursor = state->select_start; } else { stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end); state->select_start = state->cursor = state->select_end; } state->has_preferred_x = 0; } } // canoncialize the selection so start <= end static void stb_textedit_sortselection(STB_TexteditState *state) { if (state->select_end < state->select_start) { int temp = state->select_end; state->select_end = state->select_start; state->select_start = temp; } } // move cursor to first character of selection static void stb_textedit_move_to_first(STB_TexteditState *state) { if (STB_TEXT_HAS_SELECTION(state)) { stb_textedit_sortselection(state); state->cursor = state->select_start; state->select_end = state->select_start; state->has_preferred_x = 0; } } // move cursor to last character of selection static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) { if (STB_TEXT_HAS_SELECTION(state)) { stb_textedit_sortselection(state); stb_textedit_clamp(str, state); state->cursor = state->select_end; state->select_start = state->select_end; state->has_preferred_x = 0; } } #ifdef STB_TEXTEDIT_IS_SPACE 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; } #ifndef STB_TEXTEDIT_MOVEWORDLEFT static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c ) { --c; // always move at least one character while( c >= 0 && !is_word_boundary( str, c ) ) --c; if( c < 0 ) c = 0; return c; } #define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous #endif #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); ++c; // always move at least one character while( c < len && !is_word_boundary( str, c ) ) ++c; if( c > len ) c = len; return c; } #define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next #endif #endif // update selection and cursor to match each other static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) { if (!STB_TEXT_HAS_SELECTION(state)) state->select_start = state->select_end = state->cursor; else state->cursor = state->select_end; } // API cut: delete selection static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) { if (STB_TEXT_HAS_SELECTION(state)) { stb_textedit_delete_selection(str,state); // implicity clamps state->has_preferred_x = 0; return 1; } return 0; } // API paste: replace existing selection with passed-in text static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len) { STB_TEXTEDIT_CHARTYPE *text = (STB_TEXTEDIT_CHARTYPE *) ctext; // if there's a selection, the paste should delete it stb_textedit_clamp(str, state); stb_textedit_delete_selection(str,state); // try to insert the characters if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) { stb_text_makeundo_insert(state, state->cursor, len); state->cursor += len; state->has_preferred_x = 0; return 1; } // remove the undo since we didn't actually insert the characters if (state->undostate.undo_point) --state->undostate.undo_point; return 0; } // API key: process a keyboard input static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int key) { retry: switch (key) { default: { int c = STB_TEXTEDIT_KEYTOTEXT(key); if (c > 0) { STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c; // can't add newline in single-line mode if (c == '\n' && state->single_line) break; if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { stb_text_makeundo_replace(str, state, state->cursor, 1, 1); STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { ++state->cursor; state->has_preferred_x = 0; } } else { stb_textedit_delete_selection(str,state); // implicity clamps if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { stb_text_makeundo_insert(state, state->cursor, 1); ++state->cursor; state->has_preferred_x = 0; } } } break; } #ifdef STB_TEXTEDIT_K_INSERT case STB_TEXTEDIT_K_INSERT: state->insert_mode = !state->insert_mode; break; #endif case STB_TEXTEDIT_K_UNDO: stb_text_undo(str, state); state->has_preferred_x = 0; break; case STB_TEXTEDIT_K_REDO: stb_text_redo(str, state); state->has_preferred_x = 0; break; case STB_TEXTEDIT_K_LEFT: // if currently there's a selection, move cursor to start of selection if (STB_TEXT_HAS_SELECTION(state)) stb_textedit_move_to_first(state); else if (state->cursor > 0) --state->cursor; state->has_preferred_x = 0; break; case STB_TEXTEDIT_K_RIGHT: // if currently there's a selection, move cursor to end of selection if (STB_TEXT_HAS_SELECTION(state)) stb_textedit_move_to_last(str, state); else ++state->cursor; stb_textedit_clamp(str, state); state->has_preferred_x = 0; break; case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT: stb_textedit_clamp(str, state); stb_textedit_prep_selection_at_cursor(state); // move selection left if (state->select_end > 0) --state->select_end; state->cursor = state->select_end; state->has_preferred_x = 0; break; #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_MOVEWORDLEFT(str, state->cursor); stb_textedit_clamp( str, state ); } break; case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT: if( !STB_TEXT_HAS_SELECTION( state ) ) stb_textedit_prep_selection_at_cursor(state); state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); 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); 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_MOVEWORDRIGHT(str, state->cursor); state->select_end = state->cursor; stb_textedit_clamp( str, state ); break; #endif case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT: stb_textedit_prep_selection_at_cursor(state); // move selection right ++state->select_end; stb_textedit_clamp(str, state); state->cursor = state->select_end; state->has_preferred_x = 0; break; case STB_TEXTEDIT_K_DOWN: case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: { StbFindState find; StbTexteditRow row; int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; if (state->single_line) { // on windows, up&down in single-line behave like left&right key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); goto retry; } if (sel) stb_textedit_prep_selection_at_cursor(state); else if (STB_TEXT_HAS_SELECTION(state)) stb_textedit_move_to_last(str,state); // compute current position of cursor point stb_textedit_clamp(str, state); stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); // now find character position down a row if (find.length) { float goal_x = state->has_preferred_x ? state->preferred_x : find.x; float x; int start = find.first_char + find.length; state->cursor = start; STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); x = row.x0; for (i=0; i < row.num_chars; ++i) { float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) break; #endif x += dx; if (x > goal_x) break; ++state->cursor; } stb_textedit_clamp(str, state); state->has_preferred_x = 1; state->preferred_x = goal_x; if (sel) state->select_end = state->cursor; } break; } case STB_TEXTEDIT_K_UP: case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: { StbFindState find; StbTexteditRow row; int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; if (state->single_line) { // on windows, up&down become left&right key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); goto retry; } if (sel) stb_textedit_prep_selection_at_cursor(state); else if (STB_TEXT_HAS_SELECTION(state)) stb_textedit_move_to_first(state); // compute current position of cursor point stb_textedit_clamp(str, state); stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); // can only go up if there's a previous row if (find.prev_first != find.first_char) { // now find character position up a row float goal_x = state->has_preferred_x ? state->preferred_x : find.x; float x; state->cursor = find.prev_first; STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); x = row.x0; for (i=0; i < row.num_chars; ++i) { float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) break; #endif x += dx; if (x > goal_x) break; ++state->cursor; } stb_textedit_clamp(str, state); state->has_preferred_x = 1; state->preferred_x = goal_x; if (sel) state->select_end = state->cursor; } break; } case STB_TEXTEDIT_K_DELETE: case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT: if (STB_TEXT_HAS_SELECTION(state)) stb_textedit_delete_selection(str, state); else { int n = STB_TEXTEDIT_STRINGLEN(str); if (state->cursor < n) stb_textedit_delete(str, state, state->cursor, 1); } state->has_preferred_x = 0; break; case STB_TEXTEDIT_K_BACKSPACE: case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT: if (STB_TEXT_HAS_SELECTION(state)) stb_textedit_delete_selection(str, state); else { stb_textedit_clamp(str, state); if (state->cursor > 0) { stb_textedit_delete(str, state, state->cursor-1, 1); --state->cursor; } } 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); state->has_preferred_x = 0; break; #ifdef STB_TEXTEDIT_K_LINESTART2 case STB_TEXTEDIT_K_LINESTART2: #endif case STB_TEXTEDIT_K_LINESTART: stb_textedit_clamp(str, state); stb_textedit_move_to_first(state); if (state->single_line) state->cursor = 0; else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) --state->cursor; state->has_preferred_x = 0; break; #ifdef STB_TEXTEDIT_K_LINEEND2 case STB_TEXTEDIT_K_LINEEND2: #endif case STB_TEXTEDIT_K_LINEEND: { int n = STB_TEXTEDIT_STRINGLEN(str); stb_textedit_clamp(str, state); stb_textedit_move_to_first(state); if (state->single_line) state->cursor = n; else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) ++state->cursor; state->has_preferred_x = 0; 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: stb_textedit_clamp(str, state); stb_textedit_prep_selection_at_cursor(state); if (state->single_line) state->cursor = 0; else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) --state->cursor; state->select_end = state->cursor; state->has_preferred_x = 0; 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: { int n = STB_TEXTEDIT_STRINGLEN(str); stb_textedit_clamp(str, state); stb_textedit_prep_selection_at_cursor(state); if (state->single_line) state->cursor = n; else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) ++state->cursor; state->select_end = state->cursor; state->has_preferred_x = 0; break; } // @TODO: // STB_TEXTEDIT_K_PGUP - move cursor up a page // STB_TEXTEDIT_K_PGDOWN - move cursor down a page } } ///////////////////////////////////////////////////////////////////////////// // // Undo processing // // @OPTIMIZE: the undo/redo buffer should be circular static void stb_textedit_flush_redo(StbUndoState *state) { state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; } // discard the oldest entry in the undo list static void stb_textedit_discard_undo(StbUndoState *state) { if (state->undo_point > 0) { // if the 0th undo state has characters, clean those up if (state->undo_rec[0].char_storage >= 0) { 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 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; STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0]))); } } // discard the oldest entry in the redo list--it's bad if this // ever happens, but because undo & redo have to store the actual // characters in different cases, the redo character buffer can // fill up even though the undo buffer didn't static void stb_textedit_discard_redo(StbUndoState *state) { int k = STB_TEXTEDIT_UNDOSTATECOUNT-1; if (state->redo_point <= k) { // if the k'th undo state has characters, clean those up if (state->undo_rec[k].char_storage >= 0) { 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 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; } } static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars) { // any time we create a new undo record, we discard redo stb_textedit_flush_redo(state); // if we have no free records, we have to make room, by sliding the // existing records down if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT) stb_textedit_discard_undo(state); // if the characters to store won't possibly fit in the buffer, we can't undo if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) { state->undo_point = 0; state->undo_char_point = 0; return NULL; } // if we don't have enough free characters in the buffer, we have to make room while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT) stb_textedit_discard_undo(state); return &state->undo_rec[state->undo_point++]; } static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len) { StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); if (r == NULL) return NULL; r->where = pos; r->insert_length = (short) insert_len; r->delete_length = (short) delete_len; if (insert_len == 0) { r->char_storage = -1; return NULL; } else { r->char_storage = state->undo_char_point; state->undo_char_point = state->undo_char_point + (short) insert_len; return &state->undo_char[r->char_storage]; } } static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) { StbUndoState *s = &state->undostate; StbUndoRecord u, *r; if (s->undo_point == 0) return; // we need to do two things: apply the undo record, and create a redo record u = s->undo_rec[s->undo_point-1]; r = &s->undo_rec[s->redo_point-1]; r->char_storage = -1; r->insert_length = u.delete_length; r->delete_length = u.insert_length; r->where = u.where; if (u.delete_length) { // if the undo record says to delete characters, then the redo record will // need to re-insert the characters that get deleted, so we need to store // them. // there are three cases: // there's enough room to store the characters // characters stored for *redoing* don't leave room for redo // characters stored for *undoing* don't leave room for redo // if the last is true, we have to bail if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) { // the undo records take up too much character space; there's no space to store the redo characters r->insert_length = 0; } else { int i; // there's definitely room to store the characters eventually while (s->undo_char_point + u.delete_length > s->redo_char_point) { // there's currently not enough room, so discard a redo record stb_textedit_discard_redo(s); // should never happen: if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) return; } r = &s->undo_rec[s->redo_point-1]; r->char_storage = s->redo_char_point - u.delete_length; s->redo_char_point = s->redo_char_point - (short) u.delete_length; // now save the characters for (i=0; i < u.delete_length; ++i) s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i); } // now we can carry out the deletion STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length); } // check type of recorded action: if (u.insert_length) { // easy case: was a deletion, so we need to insert n characters STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); s->undo_char_point -= u.insert_length; } state->cursor = u.where + u.insert_length; s->undo_point--; s->redo_point--; } static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) { StbUndoState *s = &state->undostate; StbUndoRecord *u, r; if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) return; // we need to do two things: apply the redo record, and create an undo record u = &s->undo_rec[s->undo_point]; r = s->undo_rec[s->redo_point]; // we KNOW there must be room for the undo record, because the redo record // was derived from an undo record u->delete_length = r.insert_length; u->insert_length = r.delete_length; u->where = r.where; u->char_storage = -1; if (r.delete_length) { // the redo record requires us to delete characters, so the undo record // needs to store the characters if (s->undo_char_point + u->insert_length > s->redo_char_point) { u->insert_length = 0; u->delete_length = 0; } else { int i; u->char_storage = s->undo_char_point; s->undo_char_point = s->undo_char_point + u->insert_length; // now save the characters for (i=0; i < u->insert_length; ++i) s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i); } STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length); } 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; s->undo_point++; s->redo_point++; } static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length) { stb_text_createundo(&state->undostate, where, 0, length); } static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length) { int i; STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0); if (p) { for (i=0; i < length; ++i) p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); } } static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length) { int i; STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length); if (p) { for (i=0; i < old_length; ++i) p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); } } // reset the state to default static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line) { state->undostate.undo_point = 0; state->undostate.undo_char_point = 0; state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; state->select_end = state->select_start = 0; state->cursor = 0; state->has_preferred_x = 0; state->preferred_x = 0; state->cursor_at_end_of_line = 0; state->initialized = 1; state->single_line = (unsigned char) is_single_line; state->insert_mode = 0; } // API initialize static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) { stb_textedit_clear_state(state, is_single_line); } #endif//STB_TEXTEDIT_IMPLEMENTATION ================================================ FILE: ui/imgui/stb_truetype.h ================================================ // stb_truetype.h - v1.19 - public domain // authored from 2009-2016 by Sean Barrett / RAD Game Tools // // This library processes TrueType files: // parse files // extract glyph metrics // extract glyph shapes // render glyphs to one-channel bitmaps with antialiasing (box filter) // render glyphs to one-channel SDF bitmaps (signed-distance field/function) // // Todo: // non-MS cmaps // crashproof on bad data // hinting? (no longer patented) // cleartype-style AA? // optimize: use simple memory allocator for intermediates // optimize: build edge-list directly from curves // optimize: rasterize directly from curves? // // ADDITIONAL CONTRIBUTORS // // Mikko Mononen: compound shape support, more cmap formats // Tor Andersson: kerning, subpixel rendering // Dougall Johnson: OpenType / Type 2 font handling // Daniel Ribeiro Maciel: basic GPOS-based kerning // // Misc other: // Ryan Gordon // Simon Glass // github:IntellectualKitty // Imanol Celaya // Daniel Ribeiro Maciel // // Bug/warning reports/fixes: // "Zer" on mollyrocket Fabian "ryg" Giesen // Cass Everitt Martins Mozeiko // stoiko (Haemimont Games) Cap Petschulat // Brian Hook Omar Cornut // Walter van Niftrik github:aloucks // David Gow Peter LaValle // David Given Sergey Popov // Ivan-Assen Ivanov Giumo X. Clanjor // Anthony Pesch Higor Euripedes // Johan Duparc Thomas Fields // Hou Qiming Derek Vinyard // Rob Loach Cort Stratton // Kenney Phillis Jr. github:oyvindjam // Brian Costabile github:vassvik // // VERSION HISTORY // // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod // 1.18 (2018-01-29) add missing function // 1.17 (2017-07-23) make more arguments const; doc fix // 1.16 (2017-07-12) SDF support // 1.15 (2017-03-03) make more arguments const // 1.14 (2017-01-16) num-fonts-in-TTC function // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual // 1.11 (2016-04-02) fix unused-variable warning // 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 // // Full history can be found at the end of this file. // // LICENSE // // See end of file for license information. // // USAGE // // Include this file in whatever places neeed to refer to it. In ONE C/C++ // file, write: // #define STB_TRUETYPE_IMPLEMENTATION // 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 // // Improved 3D API (more shippable): // #include "stb_rect_pack.h" -- optional, but you really want it // stbtt_PackBegin() // stbtt_PackSetOversampling() -- for improved quality on small fonts // stbtt_PackFontRanges() -- pack and renders // stbtt_PackEnd() // stbtt_GetPackedQuad() // // "Load" a font file from a memory buffer (you have to keep the buffer loaded) // stbtt_InitFont() // stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections // stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections // // Render a unicode codepoint to a bitmap // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be // // Character advance/positioning // stbtt_GetCodepointHMetrics() // stbtt_GetFontVMetrics() // stbtt_GetFontVMetricsOS2() // 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. // // After the sample programs is the "header file" section. This section // includes documentation for each API function. // // Some important concepts to understand to use this library: // // Codepoint // Characters are defined by unicode codepoints, e.g. 65 is // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is // the hiragana for "ma". // // Glyph // A visual character shape (every codepoint is rendered as // some glyph) // // Glyph index // A font-specific integer ID representing a glyph // // Baseline // Glyph shapes are defined relative to a baseline, which is the // bottom of uppercase characters. Characters extend both above // and below the baseline. // // Current Point // As you draw text to the screen, you keep track of a "current point" // which is the origin of each character. The current point's vertical // position is the baseline. Even "baked fonts" use this model. // // Vertical Font Metrics // The vertical qualities of the font, used to vertically position // and space the characters. See docs for stbtt_GetFontVMetrics. // // Font Size in Pixels or Points // The preferred interface for specifying font sizes in stb_truetype // is to specify how tall the font's vertical extent should be in pixels. // If that sounds good enough, skip the next paragraph. // // Most font APIs instead use "points", which are a common typographic // measurement for describing font size, defined as 72 points per inch. // stb_truetype provides a point API for compatibility. However, true // "per inch" conventions don't make much sense on computer displays // since different monitors have different number of pixels per // inch. For example, Windows traditionally uses a convention that // there are 96 pixels per inch, thus making 'inch' measurements have // nothing to do with inches, and thus effectively defining a point to // be 1.333 pixels. Additionally, the TrueType font data provides // an explicit scale factor to scale a given font's glyphs to points, // but the author has observed that this scale factor is often wrong // for non-commercial fonts, thus making fonts scaled in points // according to the TrueType spec incoherently sized in practice. // // DETAILED USAGE: // // Scale: // Select how high you want the font to be, in points or pixels. // Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute // a scale factor SF that will be used by all other functions. // // Baseline: // You need to select a y-coordinate that is the baseline of where // your text will appear. Call GetFontBoundingBox to get the baseline-relative // bounding box for all characters. SF*-y0 will be the distance in pixels // that the worst-case character could extend above the baseline, so if // you want the top edge of characters to appear at the top of the // screen where y=0, then you would set the baseline to SF*-y0. // // Current point: // Set the current point where the first character will appear. The // first character could extend left of the current point; this is font // dependent. You can either choose a current point that is the leftmost // point and hope, or add some padding, or check the bounding box or // left-side-bearing of the first character to be displayed and set // the current point based on that. // // Displaying a character: // Compute the bounding box of the character. It will contain signed values // relative to . I.e. if it returns x0,y0,x1,y1, // then the character should be displayed in the rectangle from // to = 32 && *text < 128) { stbtt_aligned_quad q; stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0); glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0); glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1); glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1); } ++text; } glEnd(); } #endif // // ////////////////////////////////////////////////////////////////////////////// // // Complete program (this compiles): get a single bitmap, print as ASCII art // #if 0 #include #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" char ttf_buffer[1<<25]; int main(int argc, char **argv) { stbtt_fontinfo font; unsigned char *bitmap; int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); for (j=0; j < h; ++j) { for (i=0; i < w; ++i) putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); putchar('\n'); } return 0; } #endif // // Output: // // .ii. // @@@@@@. // V@Mio@@o // :i. V@V // :oM@@M // :@@@MM@M // @@o o@M // :@@. M@M // @@@o@@@@ // :M@@V:@@. // ////////////////////////////////////////////////////////////////////////////// // // Complete program: print "Hello World!" banner, with bugs // #if 0 char buffer[24<<20]; unsigned char screen[20][79]; 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!"; // intentionally misspelled to show 'lj' brokenness fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, buffer, 0); scale = stbtt_ScaleForPixelHeight(&font, 15); stbtt_GetFontVMetrics(&font, &ascent,0,0); baseline = (int) (ascent*scale); while (text[ch]) { int advance,lsb,x0,y0,x1,y1; float x_shift = xpos - (float) floor(xpos); stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong // because this API is really for baking character bitmaps into textures. if you want to render // a sequence of characters, you really need to render each bitmap to a temp buffer, then // "alpha blend" that into the working buffer xpos += (advance * scale); if (text[ch+1]) xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); ++ch; } for (j=0; j < 20; ++j) { for (i=0; i < 78; ++i) putchar(" .:ioVM@"[screen[j][i]>>5]); putchar('\n'); } return 0; } #endif ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //// //// INTEGRATION WITH YOUR CODEBASE //// //// The following sections allow you to supply alternate definitions //// of C library functions used by stb_truetype, e.g. if you don't //// link with the C runtime library. #ifdef STB_TRUETYPE_IMPLEMENTATION // #define your own (u)stbtt_int8/16/32 before including to override this #ifndef stbtt_uint8 typedef unsigned char stbtt_uint8; typedef signed char stbtt_int8; typedef unsigned short stbtt_uint16; typedef signed short stbtt_int16; typedef unsigned int stbtt_uint32; typedef signed int stbtt_int32; #endif typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h #ifndef STBTT_ifloor #include #define STBTT_ifloor(x) ((int) floor(x)) #define STBTT_iceil(x) ((int) ceil(x)) #endif #ifndef STBTT_sqrt #include #define STBTT_sqrt(x) sqrt(x) #define STBTT_pow(x,y) pow(x,y) #endif #ifndef STBTT_fmod #include #define STBTT_fmod(x,y) fmod(x,y) #endif #ifndef STBTT_cos #include #define STBTT_cos(x) cos(x) #define STBTT_acos(x) acos(x) #endif #ifndef STBTT_fabs #include #define STBTT_fabs(x) fabs(x) #endif // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h #ifndef STBTT_malloc #include #define STBTT_malloc(x,u) ((void)(u),malloc(x)) #define STBTT_free(x,u) ((void)(u),free(x)) #endif #ifndef STBTT_assert #include #define STBTT_assert(x) assert(x) #endif #ifndef STBTT_strlen #include #define STBTT_strlen(x) strlen(x) #endif #ifndef STBTT_memcpy #include #define STBTT_memcpy memcpy #define STBTT_memset memset #endif #endif /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //// //// INTERFACE //// //// #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 // private structure typedef struct { unsigned char *data; int cursor; int size; } stbtt__buf; ////////////////////////////////////////////////////////////////////////////// // // TEXTURE BAKING API // // If you use this API, you only have to call two functions ever. // typedef struct { unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap float xoff,yoff,xadvance; } stbtt_bakedchar; STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake stbtt_bakedchar *chardata); // you allocate this, it's num_chars long // if return is positive, the first unused row of the bitmap // if return is negative, returns the negative of the number of characters that fit // if return is 0, no characters fit and no rows were used // This uses a very crappy packing. typedef struct { float x0,y0,s0,t0; // top-left float x1,y1,s1,t1; // bottom-right } stbtt_aligned_quad; STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display float *xpos, float *ypos, // pointers to current position in screen pixel space stbtt_aligned_quad *q, // output: quad to draw int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier // Call GetBakedQuad with char_index = 'character - first_char', and it // creates the quad you need to draw and advances the current position. // // The coordinate system used assumes y increases downwards. // // Characters will extend both above and below the current position; // see discussion of "BASELINE" above. // // It's inefficient; you might want to c&p it and optimize it. ////////////////////////////////////////////////////////////////////////////// // // NEW TEXTURE BAKING API // // This provides options for packing multiple fonts into one atlas, not // perfectly but better than nothing. typedef struct { unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap float xoff,yoff,xadvance; float xoff2,yoff2; } stbtt_packedchar; typedef struct stbtt_pack_context stbtt_pack_context; typedef struct stbtt_fontinfo stbtt_fontinfo; #ifndef STB_RECT_PACK_VERSION typedef struct stbrp_rect stbrp_rect; #endif STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); // Initializes a packing context stored in the passed-in stbtt_pack_context. // Future calls using this context will pack characters into the bitmap passed // in here: a 1-channel bitmap that is width * 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 // character (normally you want '1' for bitmaps you'll use as textures with // bilinear filtering). // // Returns 0 on failure, 1 on success. STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); // Cleans up the packing context and frees all memory. #define STBTT_POINT_SIZE(x) (-(x)) STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const 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); // Creates character bitmaps from the font_index'th font found in fontdata (use // font_index=0 if you don't know what that is). It creates num_chars_in_range // bitmaps for characters with unicode values starting at first_unicode_char_in_range // and increasing. Data for how to render them is stored in chardata_for_range; // pass these to stbtt_GetPackedQuad to get back renderable quads. // // font_size is the full height of the character from ascender to descender, // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() // and pass that result as 'font_size': // ..., 20 , ... // font max minus min y is 20 pixels tall // ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall typedef struct { float font_size; 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, const 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. 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) 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(const stbtt_packedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display float *xpos, float *ypos, // pointers to current position in screen pixel space stbtt_aligned_quad *q, // output: quad to draw int align_to_integer); STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const 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, const 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 { void *user_allocator_context; void *pack_info; int width; int height; int stride_in_bytes; int padding; unsigned int h_oversample, v_oversample; unsigned char *pixels; void *nodes; }; ////////////////////////////////////////////////////////////////////////////// // // FONT LOADING // // STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); // This function will determine the number of fonts in a font file. TrueType // collection (.ttc) files may contain multiple fonts, while TrueType font // (.ttf) files only contain one font. The number of fonts can be used for // indexing with the previous function where the index is between zero and one // less than the total fonts. If an error occurs, -1 is returned. STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); // Each .ttf/.ttc file may have more than one font. Each font has a sequential // index number starting from 0. Call this function to get the font offset for // a given index; it returns -1 if the index is out of range. A regular .ttf // file will only define one font and it always be at offset 0, so it will // return '0' for index 0, and -1 for all other indices. // 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. struct stbtt_fontinfo { void * userdata; unsigned char * data; // pointer to .ttf file int fontstart; // offset of start of font int numGlyphs; // number of glyphs, needed for range checking int loca,head,glyf,hhea,hmtx,kern,gpos; // 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__buf cff; // cff font data stbtt__buf charstrings; // the charstring index stbtt__buf gsubrs; // global charstring subroutines index stbtt__buf subrs; // private charstring subroutines index stbtt__buf fontdicts; // array of font dicts stbtt__buf fdselect; // map from glyph to fontdict }; 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 // the necessary cached info for the rest of the system. You must allocate // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't // need to do anything special to free it, because the contents are pure // value data with no additional data structures. Returns 0 on failure. ////////////////////////////////////////////////////////////////////////////// // // CHARACTER TO GLYPH-INDEX CONVERSIOn STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); // If you're going to perform multiple operations on the same character // and you want a speed-up, call this function with the character you're // going to process, then use glyph-based functions instead of the // codepoint-based functions. ////////////////////////////////////////////////////////////////////////////// // // CHARACTER PROPERTIES // STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose "height" is 'pixels' tall. // Height is measured as the distance from the highest ascender to the lowest // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics // and computing: // scale = pixels / (ascent - descent) // so if you prefer to measure height by the ascent only, use a similar calculation. STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose EM size is mapped to // 'pixels' tall. This is probably what traditional APIs compute, but // I'm not positive. STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); // ascent is the coordinate above the baseline the font extends; descent // is the coordinate below the baseline the font extends (i.e. it is typically negative) // lineGap is the spacing between one row's descent and the next row's ascent... // so you should advance the vertical position by "*ascent - *descent + *lineGap" // these are expressed in unscaled coordinates, so you must multiply by // the scale factor for a given size STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 // table (specific to MS/Windows TTF files). // // Returns 1 on success (table present), 0 on failure. STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); // the bounding box around all possible characters STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); // leftSideBearing is the offset from the current horizontal position to the left edge of the character // advanceWidth is the offset from the current horizontal position to the next horizontal position // these are expressed in unscaled coordinates STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); // an additional amount to add to the 'advance' value between ch1 and ch2 STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); // Gets the bounding box of the visible part of the glyph, in unscaled coordinates STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); // as above, but takes one or more glyph indices for greater efficiency ////////////////////////////////////////////////////////////////////////////// // // GLYPH SHAPES (you probably don't need these, but they have to go before // the bitmaps for C declaration-order reasons) // #ifndef STBTT_vmove // you can predefine these to use different values (but why?) enum { STBTT_vmove=1, STBTT_vline, STBTT_vcurve, STBTT_vcubic }; #endif #ifndef stbtt_vertex // you can predefine this to use different values // (we share this with other code at RAD) #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file typedef struct { stbtt_vertex_type x,y,cx,cy,cx1,cy1; unsigned char type,padding; } stbtt_vertex; #endif STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); // returns non-zero if nothing is drawn for this glyph STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); // returns # of vertices and fills *vertices with the pointer to them // these are expressed in "unscaled" coordinates // // The shape is a series of countours. Each one starts with // a STBTT_moveto, then consists of a series of mixed // STBTT_lineto and STBTT_curveto segments. A lineto // draws a line from previous endpoint to its x,y; a curveto // draws a quadratic bezier from previous endpoint to // its x,y, using cx,cy as the bezier control point. STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); // frees the data allocated above ////////////////////////////////////////////////////////////////////////////// // // BITMAP RENDERING // STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); // frees the bitmap allocated below STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); // allocates a large-enough single-channel 8bpp bitmap and renders the // specified character/glyph at the specified scale into it, with // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). // *width & *height are filled out with the width & height of the bitmap, // which is stored left-to-right, top-to-bottom. // // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel // shift for the character STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the // width and height and positioning info for it first. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel // shift for the character STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); // same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering // is performed (see stbtt_PackSetOversampling) STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); // get the bbox of the bitmap centered around the glyph origin; so the // bitmap width is ix1-ix0, height is iy1-iy0, and location to place // the bitmap top left is (leftSideBearing*scale,iy0). // (Note that the bitmap uses y-increases-down, but the shape uses // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel // shift for the character // the following functions are equivalent to the above functions, but operate // on glyph indices instead of Unicode codepoints (for efficiency) STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); 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); // @TODO: don't expose this structure typedef struct { int w,h,stride; unsigned char *pixels; } stbtt__bitmap; // 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 ////////////////////////////////////////////////////////////////////////////// // // Signed Distance Function (or Field) rendering STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); // frees the SDF bitmap allocated below STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); // These functions compute a discretized SDF field for a single character, suitable for storing // in a single-channel texture, sampling with bilinear filtering, and testing against // larger than some threshhold to produce scalable fonts. // info -- the font // scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap // glyph/codepoint -- the character to generate the SDF for // padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), // which allows effects like bit outlines // onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) // pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) // if positive, > onedge_value is inside; if negative, < onedge_value is inside // width,height -- output height & width of the SDF bitmap (including padding) // xoff,yoff -- output origin of the character // return value -- a 2D array of bytes 0..255, width*height in size // // pixel_dist_scale & onedge_value are a scale & bias that allows you to make // optimal use of the limited 0..255 for your application, trading off precision // and special effects. SDF values outside the range 0..255 are clamped to 0..255. // // Example: // scale = stbtt_ScaleForPixelHeight(22) // padding = 5 // onedge_value = 180 // pixel_dist_scale = 180/5.0 = 36.0 // // This will create an SDF bitmap in which the character is about 22 pixels // high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled // shape, sample the SDF at each pixel and fill the pixel if the SDF value // is greater than or equal to 180/255. (You'll actually want to antialias, // which is beyond the scope of this example.) Additionally, you can compute // offset outlines (e.g. to stroke the character border inside & outside, // or only outside). For example, to fill outside the character up to 3 SDF // pixels, you would compare against (180-36.0*3)/255 = 72/255. The above // choice of variables maps a range from 5 pixels outside the shape to // 2 pixels inside the shape to 0..255; this is intended primarily for apply // outside effects only (the interior range is needed to allow proper // antialiasing of the font at *smaller* sizes) // // The function computes the SDF analytically at each SDF pixel, not by e.g. // building a higher-res bitmap and approximating it. In theory the quality // should be as high as possible for an SDF of this size & representation, but // unclear if this is true in practice (perhaps building a higher-res bitmap // and computing from that can allow drop-out prevention). // // The algorithm has not been optimized at all, so expect it to be slow // if computing lots of characters or very large sizes. ////////////////////////////////////////////////////////////////////////////// // // Finding the right font... // // You should really just solve this offline, keep your own tables // of what font is what, and don't try to get it out of the .ttf file. // That's because getting it out of the .ttf file is really hard, because // the names in the file can appear in many possible encodings, in many // possible languages, and e.g. if you need a case-insensitive comparison, // the details of that depend on the encoding & language in a complex way // (actually underspecified in truetype, but also gigantic). // // But you can use the provided functions in two possible ways: // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on // unicode-encoded names to try to find the font you want; // you can run this before calling stbtt_InitFont() // // stbtt_GetFontNameString() lets you get any of the various strings // from the file yourself and do your own comparisons on them. // You have to have called stbtt_InitFont() first. STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); // returns the offset (not index) of the font that matches, or -1 if none // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". // if you use any other flag, use a font name like "Arial"; this checks // the 'macStyle' header field; i don't know if fonts set this consistently #define STBTT_MACSTYLE_DONTCARE 0 #define STBTT_MACSTYLE_BOLD 1 #define STBTT_MACSTYLE_ITALIC 2 #define STBTT_MACSTYLE_UNDERSCORE 4 #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); // returns 1/0 whether the first string interpreted as utf8 is identical to // the second string interpreted as big-endian utf16... useful for strings from next func STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); // returns the string (which may be big-endian double byte, e.g. for unicode) // and puts the length in bytes in *length. // // some of the values for the IDs are below; for more see the truetype spec: // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html // http://www.microsoft.com/typography/otspec/name.htm enum { // platformID STBTT_PLATFORM_ID_UNICODE =0, STBTT_PLATFORM_ID_MAC =1, STBTT_PLATFORM_ID_ISO =2, STBTT_PLATFORM_ID_MICROSOFT =3 }; enum { // encodingID for STBTT_PLATFORM_ID_UNICODE STBTT_UNICODE_EID_UNICODE_1_0 =0, STBTT_UNICODE_EID_UNICODE_1_1 =1, STBTT_UNICODE_EID_ISO_10646 =2, STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 }; enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT STBTT_MS_EID_SYMBOL =0, STBTT_MS_EID_UNICODE_BMP =1, STBTT_MS_EID_SHIFTJIS =2, STBTT_MS_EID_UNICODE_FULL =10 }; enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 }; enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D }; enum { // languageID for STBTT_PLATFORM_ID_MAC STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 }; #ifdef __cplusplus } #endif #endif // __STB_INCLUDE_STB_TRUETYPE_H__ /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //// //// IMPLEMENTATION //// //// #ifdef STB_TRUETYPE_IMPLEMENTATION #ifndef STBTT_MAX_OVERSAMPLE #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 #ifdef _MSC_VER #define STBTT__NOTUSED(v) (void)(v) #else #define STBTT__NOTUSED(v) (void)sizeof(v) #endif ////////////////////////////////////////////////////////////////////////// // // stbtt__buf helpers to parse data from file // static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) { if (b->cursor >= b->size) return 0; return b->data[b->cursor++]; } static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) { if (b->cursor >= b->size) return 0; return b->data[b->cursor]; } static void stbtt__buf_seek(stbtt__buf *b, int o) { STBTT_assert(!(o > b->size || o < 0)); b->cursor = (o > b->size || o < 0) ? b->size : o; } static void stbtt__buf_skip(stbtt__buf *b, int o) { stbtt__buf_seek(b, b->cursor + o); } static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) { stbtt_uint32 v = 0; int i; STBTT_assert(n >= 1 && n <= 4); for (i = 0; i < n; i++) v = (v << 8) | stbtt__buf_get8(b); return v; } static stbtt__buf stbtt__new_buf(const void *p, size_t size) { stbtt__buf r; STBTT_assert(size < 0x40000000); r.data = (stbtt_uint8*) p; r.size = (int) size; r.cursor = 0; return r; } #define stbtt__buf_get16(b) stbtt__buf_get((b), 2) #define stbtt__buf_get32(b) stbtt__buf_get((b), 4) static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) { stbtt__buf r = stbtt__new_buf(NULL, 0); if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; r.data = b->data + o; r.size = s; return r; } static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) { int count, start, offsize; start = b->cursor; count = stbtt__buf_get16(b); if (count) { offsize = stbtt__buf_get8(b); STBTT_assert(offsize >= 1 && offsize <= 4); stbtt__buf_skip(b, offsize * count); stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); } return stbtt__buf_range(b, start, b->cursor - start); } static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) { int b0 = stbtt__buf_get8(b); if (b0 >= 32 && b0 <= 246) return b0 - 139; else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; else if (b0 == 28) return stbtt__buf_get16(b); else if (b0 == 29) return stbtt__buf_get32(b); STBTT_assert(0); return 0; } static void stbtt__cff_skip_operand(stbtt__buf *b) { int v, b0 = stbtt__buf_peek8(b); STBTT_assert(b0 >= 28); if (b0 == 30) { stbtt__buf_skip(b, 1); while (b->cursor < b->size) { v = stbtt__buf_get8(b); if ((v & 0xF) == 0xF || (v >> 4) == 0xF) break; } } else { stbtt__cff_int(b); } } static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) { stbtt__buf_seek(b, 0); while (b->cursor < b->size) { int start = b->cursor, end, op; while (stbtt__buf_peek8(b) >= 28) stbtt__cff_skip_operand(b); end = b->cursor; op = stbtt__buf_get8(b); if (op == 12) op = stbtt__buf_get8(b) | 0x100; if (op == key) return stbtt__buf_range(b, start, end-start); } return stbtt__buf_range(b, 0, 0); } static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) { int i; stbtt__buf operands = stbtt__dict_get(b, key); for (i = 0; i < outcount && operands.cursor < operands.size; i++) out[i] = stbtt__cff_int(&operands); } static int stbtt__cff_index_count(stbtt__buf *b) { stbtt__buf_seek(b, 0); return stbtt__buf_get16(b); } static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) { int count, offsize, start, end; stbtt__buf_seek(&b, 0); count = stbtt__buf_get16(&b); offsize = stbtt__buf_get8(&b); STBTT_assert(i >= 0 && i < count); STBTT_assert(offsize >= 1 && offsize <= 4); stbtt__buf_skip(&b, i*offsize); start = stbtt__buf_get(&b, offsize); end = stbtt__buf_get(&b, offsize); return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); } ////////////////////////////////////////////////////////////////////////// // // accessors to parse data from file // // on platforms that don't allow misaligned reads, if we want to allow // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE #define ttBYTE(p) (* (stbtt_uint8 *) (p)) #define ttCHAR(p) (* (stbtt_int8 *) (p)) #define ttFixed(p) ttLONG(p) static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) static int stbtt__isfont(stbtt_uint8 *font) { // check the version number if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts return 0; } // @OPTIMIZE: binary search static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) { stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); stbtt_uint32 tabledir = fontstart + 12; stbtt_int32 i; for (i=0; i < num_tables; ++i) { stbtt_uint32 loc = tabledir + 16*i; if (stbtt_tag(data+loc+0, tag)) return ttULONG(data+loc+8); } return 0; } static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) { // if it's just a font, there's only one valid index if (stbtt__isfont(font_collection)) return index == 0 ? 0 : -1; // check if it's a TTC if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { stbtt_int32 n = ttLONG(font_collection+8); if (index >= n) return -1; return ttULONG(font_collection+12+index*4); } } return -1; } static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) { // if it's just a font, there's only one valid font if (stbtt__isfont(font_collection)) return 1; // check if it's a TTC if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { return ttLONG(font_collection+8); } } return 0; } static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) { stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; stbtt__buf pdict; stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); if (!subrsoff) return stbtt__new_buf(NULL, 0); stbtt__buf_seek(&cff, private_loc[1]+subrsoff); return stbtt__cff_get_index(&cff); } static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) { stbtt_uint32 cmap, t; stbtt_int32 i,numTables; info->data = data; info->fontstart = fontstart; info->cff = stbtt__new_buf(NULL, 0); cmap = stbtt__find_table(data, fontstart, "cmap"); // required info->loca = stbtt__find_table(data, fontstart, "loca"); // required info->head = stbtt__find_table(data, fontstart, "head"); // required info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required info->kern = stbtt__find_table(data, fontstart, "kern"); // not required info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required if (!cmap || !info->head || !info->hhea || !info->hmtx) return 0; if (info->glyf) { // required for truetype if (!info->loca) return 0; } else { // initialization for CFF / Type2 fonts (OTF) stbtt__buf b, topdict, topdictidx; stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; stbtt_uint32 cff; cff = stbtt__find_table(data, fontstart, "CFF "); if (!cff) return 0; info->fontdicts = stbtt__new_buf(NULL, 0); info->fdselect = stbtt__new_buf(NULL, 0); // @TODO this should use size from table (not 512MB) info->cff = stbtt__new_buf(data+cff, 512*1024*1024); b = info->cff; // read the header stbtt__buf_skip(&b, 2); stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize // @TODO the name INDEX could list multiple fonts, // but we just use the first one. stbtt__cff_get_index(&b); // name INDEX topdictidx = stbtt__cff_get_index(&b); topdict = stbtt__cff_index_get(topdictidx, 0); stbtt__cff_get_index(&b); // string INDEX info->gsubrs = stbtt__cff_get_index(&b); stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); info->subrs = stbtt__get_subrs(b, topdict); // we only support Type 2 charstrings if (cstype != 2) return 0; if (charstrings == 0) return 0; if (fdarrayoff) { // looks like a CID font if (!fdselectoff) return 0; stbtt__buf_seek(&b, fdarrayoff); info->fontdicts = stbtt__cff_get_index(&b); info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); } stbtt__buf_seek(&b, charstrings); info->charstrings = stbtt__cff_get_index(&b); } t = stbtt__find_table(data, fontstart, "maxp"); if (t) info->numGlyphs = ttUSHORT(data+t+4); else info->numGlyphs = 0xffff; // find a cmap encoding table we understand *now* to avoid searching // later. (todo: could make this installable) // the same regardless of glyph. numTables = ttUSHORT(data + cmap + 2); info->index_map = 0; for (i=0; i < numTables; ++i) { stbtt_uint32 encoding_record = cmap + 4 + 8 * i; // find an encoding we understand: switch(ttUSHORT(data+encoding_record)) { case STBTT_PLATFORM_ID_MICROSOFT: switch (ttUSHORT(data+encoding_record+2)) { case STBTT_MS_EID_UNICODE_BMP: case STBTT_MS_EID_UNICODE_FULL: // MS/Unicode info->index_map = cmap + ttULONG(data+encoding_record+4); break; } break; case STBTT_PLATFORM_ID_UNICODE: // Mac/iOS has these // all the encodingIDs are unicode, so we don't bother to check it info->index_map = cmap + ttULONG(data+encoding_record+4); break; } } if (info->index_map == 0) return 0; info->indexToLocFormat = ttUSHORT(data+info->head + 50); return 1; } STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) { stbtt_uint8 *data = info->data; stbtt_uint32 index_map = info->index_map; stbtt_uint16 format = ttUSHORT(data + index_map + 0); if (format == 0) { // apple byte encoding stbtt_int32 bytes = ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) return ttBYTE(data + index_map + 6 + unicode_codepoint); return 0; } else if (format == 6) { stbtt_uint32 first = ttUSHORT(data + index_map + 6); stbtt_uint32 count = ttUSHORT(data + index_map + 8); if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); return 0; } else if (format == 2) { STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean return 0; } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; 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; // do a binary search of the segments stbtt_uint32 endCount = index_map + 14; stbtt_uint32 search = endCount; if (unicode_codepoint > 0xffff) return 0; // they lie from endCount .. endCount + segCount // but searchRange is the nearest power of two, so... if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) search += rangeShift*2; // now decrement to bias correctly to find smallest search -= 2; while (entrySelector) { stbtt_uint16 end; searchRange >>= 1; end = ttUSHORT(data + search + searchRange*2); if (unicode_codepoint > end) search += searchRange*2; --entrySelector; } search += 2; { 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); 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)); 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; low = 0; high = (stbtt_int32)ngroups; // Binary search the right group. while (low < high) { stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); if ((stbtt_uint32) unicode_codepoint < start_char) high = mid; else if ((stbtt_uint32) unicode_codepoint > end_char) low = mid+1; else { stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); if (format == 12) return start_glyph + unicode_codepoint-start_char; else // format == 13 return start_glyph; } } return 0; // not found } // @TODO STBTT_assert(0); return 0; } STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) { return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); } static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) { v->type = type; v->x = (stbtt_int16) x; v->y = (stbtt_int16) y; v->cx = (stbtt_int16) cx; v->cy = (stbtt_int16) cy; } static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) { int g1,g2; STBTT_assert(!info->cff.size); if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format if (info->indexToLocFormat == 0) { g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; } else { g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); } return g1==g2 ? -1 : g1; // if length is 0, return -1 } static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { if (info->cff.size) { stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); } else { int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; if (x0) *x0 = ttSHORT(info->data + g + 2); if (y0) *y0 = ttSHORT(info->data + g + 4); if (x1) *x1 = ttSHORT(info->data + g + 6); if (y1) *y1 = ttSHORT(info->data + g + 8); } return 1; } STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) { return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); } STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) { stbtt_int16 numberOfContours; int g; if (info->cff.size) return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 1; numberOfContours = ttSHORT(info->data + g); return numberOfContours == 0; } static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) { if (start_off) { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); } return num_vertices; } static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { stbtt_int16 numberOfContours; stbtt_uint8 *endPtsOfContours; stbtt_uint8 *data = info->data; stbtt_vertex *vertices=0; int num_vertices=0; int g = stbtt__GetGlyfOffset(info, glyph_index); *pvertices = NULL; if (g < 0) return 0; numberOfContours = ttSHORT(data + g); if (numberOfContours > 0) { stbtt_uint8 flags=0,flagcount; stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; stbtt_uint8 *points; endPtsOfContours = (data + g + 10); ins = ttUSHORT(data + g + 10 + numberOfContours * 2); points = data + g + 10 + numberOfContours * 2 + 2 + ins; n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); m = n + 2*numberOfContours; // a loose bound on how many vertices we might need vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); if (vertices == 0) return 0; next_move = 0; flagcount=0; // in first pass, we load uninterpreted data into the allocated array // above, shifted to the end of the array so we won't overwrite it when // we create our final data starting from the front off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated // first load flags for (i=0; i < n; ++i) { if (flagcount == 0) { flags = *points++; if (flags & 8) flagcount = *points++; } else --flagcount; vertices[off+i].type = flags; } // now load x coordinates x=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 2) { stbtt_int16 dx = *points++; x += (flags & 16) ? dx : -dx; // ??? } else { if (!(flags & 16)) { x = x + (stbtt_int16) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].x = (stbtt_int16) x; } // now load y coordinates y=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 4) { stbtt_int16 dy = *points++; y += (flags & 32) ? dy : -dy; // ??? } else { if (!(flags & 32)) { y = y + (stbtt_int16) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].y = (stbtt_int16) y; } // now convert them to our format num_vertices=0; sx = sy = cx = cy = scx = scy = 0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; x = (stbtt_int16) vertices[off+i].x; y = (stbtt_int16) vertices[off+i].y; if (next_move == i) { if (i != 0) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); // now start the new one start_off = !(flags & 1); if (start_off) { // if we start off with an off-curve point, then when we need to find a point on the curve // where we can start, and we need to save some state for when we wraparound. scx = x; scy = y; if (!(vertices[off+i+1].type & 1)) { // next point is also a curve point, so interpolate an on-point curve sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; } else { // otherwise just use the next point as our start point sx = (stbtt_int32) vertices[off+i+1].x; sy = (stbtt_int32) vertices[off+i+1].y; ++i; // we're using point i+1 as the starting point, so skip it } } else { sx = x; sy = y; } stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); was_off = 0; next_move = 1 + ttUSHORT(endPtsOfContours+j*2); ++j; } else { if (!(flags & 1)) { // if it's a curve if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); cx = x; cy = y; was_off = 1; } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); was_off = 0; } } } num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); } else if (numberOfContours == -1) { // Compound shapes. int more = 1; stbtt_uint8 *comp = data + g + 10; num_vertices = 0; vertices = 0; while (more) { stbtt_uint16 flags, gidx; int comp_num_verts = 0, i; stbtt_vertex *comp_verts = 0, *tmp = 0; float mtx[6] = {1,0,0,1,0,0}, m, n; flags = ttSHORT(comp); comp+=2; gidx = ttSHORT(comp); comp+=2; if (flags & 2) { // XY values if (flags & 1) { // shorts mtx[4] = ttSHORT(comp); comp+=2; mtx[5] = ttSHORT(comp); comp+=2; } else { mtx[4] = ttCHAR(comp); comp+=1; mtx[5] = ttCHAR(comp); comp+=1; } } else { // @TODO handle matching point STBTT_assert(0); } if (flags & (1<<3)) { // WE_HAVE_A_SCALE mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } // Find transformation scales. m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); // Get indexed glyph. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); if (comp_num_verts > 0) { // Transform vertices. for (i = 0; i < comp_num_verts; ++i) { stbtt_vertex* v = &comp_verts[i]; stbtt_vertex_type x,y; x=v->x; y=v->y; v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); x=v->cx; y=v->cy; v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); } // Append vertices. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); if (!tmp) { if (vertices) STBTT_free(vertices, info->userdata); if (comp_verts) STBTT_free(comp_verts, info->userdata); return 0; } if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); if (vertices) STBTT_free(vertices, info->userdata); vertices = tmp; STBTT_free(comp_verts, info->userdata); num_vertices += comp_num_verts; } // More components ? more = flags & (1<<5); } } else if (numberOfContours < 0) { // @TODO other compound variations? STBTT_assert(0); } else { // numberOfCounters == 0, do nothing } *pvertices = vertices; return num_vertices; } typedef struct { int bounds; int started; float first_x, first_y; float x, y; stbtt_int32 min_x, max_x, min_y, max_y; stbtt_vertex *pvertices; int num_vertices; } stbtt__csctx; #define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) { if (x > c->max_x || !c->started) c->max_x = x; if (y > c->max_y || !c->started) c->max_y = y; if (x < c->min_x || !c->started) c->min_x = x; if (y < c->min_y || !c->started) c->min_y = y; c->started = 1; } static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) { if (c->bounds) { stbtt__track_vertex(c, x, y); if (type == STBTT_vcubic) { stbtt__track_vertex(c, cx, cy); stbtt__track_vertex(c, cx1, cy1); } } else { stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; } c->num_vertices++; } static void stbtt__csctx_close_shape(stbtt__csctx *ctx) { if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); } static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) { stbtt__csctx_close_shape(ctx); ctx->first_x = ctx->x = ctx->x + dx; ctx->first_y = ctx->y = ctx->y + dy; stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); } static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) { ctx->x += dx; ctx->y += dy; stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); } static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { float cx1 = ctx->x + dx1; float cy1 = ctx->y + dy1; float cx2 = cx1 + dx2; float cy2 = cy1 + dy2; ctx->x = cx2 + dx3; ctx->y = cy2 + dy3; stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); } static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) { int count = stbtt__cff_index_count(&idx); int bias = 107; if (count >= 33900) bias = 32768; else if (count >= 1240) bias = 1131; n += bias; if (n < 0 || n >= count) return stbtt__new_buf(NULL, 0); return stbtt__cff_index_get(idx, n); } static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) { stbtt__buf fdselect = info->fdselect; int nranges, start, end, v, fmt, fdselector = -1, i; stbtt__buf_seek(&fdselect, 0); fmt = stbtt__buf_get8(&fdselect); if (fmt == 0) { // untested stbtt__buf_skip(&fdselect, glyph_index); fdselector = stbtt__buf_get8(&fdselect); } else if (fmt == 3) { nranges = stbtt__buf_get16(&fdselect); start = stbtt__buf_get16(&fdselect); for (i = 0; i < nranges; i++) { v = stbtt__buf_get8(&fdselect); end = stbtt__buf_get16(&fdselect); if (glyph_index >= start && glyph_index < end) { fdselector = v; break; } start = end; } } if (fdselector == -1) stbtt__new_buf(NULL, 0); return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); } static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) { int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; int has_subrs = 0, clear_stack; float s[48]; stbtt__buf subr_stack[10], subrs = info->subrs, b; float f; #define STBTT__CSERR(s) (0) // this currently ignores the initial width value, which isn't needed if we have hmtx b = stbtt__cff_index_get(info->charstrings, glyph_index); while (b.cursor < b.size) { i = 0; clear_stack = 1; b0 = stbtt__buf_get8(&b); switch (b0) { // @TODO implement hinting case 0x13: // hintmask case 0x14: // cntrmask if (in_header) maskbits += (sp / 2); // implicit "vstem" in_header = 0; stbtt__buf_skip(&b, (maskbits + 7) / 8); break; case 0x01: // hstem case 0x03: // vstem case 0x12: // hstemhm case 0x17: // vstemhm maskbits += (sp / 2); break; case 0x15: // rmoveto in_header = 0; if (sp < 2) return STBTT__CSERR("rmoveto stack"); stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); break; case 0x04: // vmoveto in_header = 0; if (sp < 1) return STBTT__CSERR("vmoveto stack"); stbtt__csctx_rmove_to(c, 0, s[sp-1]); break; case 0x16: // hmoveto in_header = 0; if (sp < 1) return STBTT__CSERR("hmoveto stack"); stbtt__csctx_rmove_to(c, s[sp-1], 0); break; case 0x05: // rlineto if (sp < 2) return STBTT__CSERR("rlineto stack"); for (; i + 1 < sp; i += 2) stbtt__csctx_rline_to(c, s[i], s[i+1]); break; // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical // starting from a different place. case 0x07: // vlineto if (sp < 1) return STBTT__CSERR("vlineto stack"); goto vlineto; case 0x06: // hlineto if (sp < 1) return STBTT__CSERR("hlineto stack"); for (;;) { if (i >= sp) break; stbtt__csctx_rline_to(c, s[i], 0); i++; vlineto: if (i >= sp) break; stbtt__csctx_rline_to(c, 0, s[i]); i++; } break; case 0x1F: // hvcurveto if (sp < 4) return STBTT__CSERR("hvcurveto stack"); goto hvcurveto; case 0x1E: // vhcurveto if (sp < 4) return STBTT__CSERR("vhcurveto stack"); for (;;) { if (i + 3 >= sp) break; stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); i += 4; hvcurveto: if (i + 3 >= sp) break; stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); i += 4; } break; case 0x08: // rrcurveto if (sp < 6) return STBTT__CSERR("rcurveline stack"); for (; i + 5 < sp; i += 6) stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); break; case 0x18: // rcurveline if (sp < 8) return STBTT__CSERR("rcurveline stack"); for (; i + 5 < sp - 2; i += 6) stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); stbtt__csctx_rline_to(c, s[i], s[i+1]); break; case 0x19: // rlinecurve if (sp < 8) return STBTT__CSERR("rlinecurve stack"); for (; i + 1 < sp - 6; i += 2) stbtt__csctx_rline_to(c, s[i], s[i+1]); if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); break; case 0x1A: // vvcurveto case 0x1B: // hhcurveto if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); f = 0.0; if (sp & 1) { f = s[i]; i++; } for (; i + 3 < sp; i += 4) { if (b0 == 0x1B) stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); else stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); f = 0.0; } break; case 0x0A: // callsubr if (!has_subrs) { if (info->fdselect.size) subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); has_subrs = 1; } // fallthrough case 0x1D: // callgsubr if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); v = (int) s[--sp]; if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); subr_stack[subr_stack_height++] = b; b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); if (b.size == 0) return STBTT__CSERR("subr not found"); b.cursor = 0; clear_stack = 0; break; case 0x0B: // return if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); b = subr_stack[--subr_stack_height]; clear_stack = 0; break; case 0x0E: // endchar stbtt__csctx_close_shape(c); return 1; case 0x0C: { // two-byte escape float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; float dx, dy; int b1 = stbtt__buf_get8(&b); switch (b1) { // @TODO These "flex" implementations ignore the flex-depth and resolution, // and always draw beziers. case 0x22: // hflex if (sp < 7) return STBTT__CSERR("hflex stack"); dx1 = s[0]; dx2 = s[1]; dy2 = s[2]; dx3 = s[3]; dx4 = s[4]; dx5 = s[5]; dx6 = s[6]; stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); break; case 0x23: // flex if (sp < 13) return STBTT__CSERR("flex stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dy3 = s[5]; dx4 = s[6]; dy4 = s[7]; dx5 = s[8]; dy5 = s[9]; dx6 = s[10]; dy6 = s[11]; //fd is s[12] stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); break; case 0x24: // hflex1 if (sp < 9) return STBTT__CSERR("hflex1 stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dx4 = s[5]; dx5 = s[6]; dy5 = s[7]; dx6 = s[8]; stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); break; case 0x25: // flex1 if (sp < 11) return STBTT__CSERR("flex1 stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dy3 = s[5]; dx4 = s[6]; dy4 = s[7]; dx5 = s[8]; dy5 = s[9]; dx6 = dy6 = s[10]; dx = dx1+dx2+dx3+dx4+dx5; dy = dy1+dy2+dy3+dy4+dy5; if (STBTT_fabs(dx) > STBTT_fabs(dy)) dy6 = -dy; else dx6 = -dx; stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); break; default: return STBTT__CSERR("unimplemented"); } } break; default: if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254)) return STBTT__CSERR("reserved operator"); // push immediate if (b0 == 255) { f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; } else { stbtt__buf_skip(&b, -1); f = (float)(stbtt_int16)stbtt__cff_int(&b); } if (sp >= 48) return STBTT__CSERR("push stack overflow"); s[sp++] = f; clear_stack = 0; break; } if (clear_stack) sp = 0; } return STBTT__CSERR("no endchar"); #undef STBTT__CSERR } static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { // runs the charstring twice, once to count and once to output (to avoid realloc) stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); output_ctx.pvertices = *pvertices; if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); return output_ctx.num_vertices; } } *pvertices = NULL; return 0; } static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { stbtt__csctx c = STBTT__CSCTX_INIT(1); int r = stbtt__run_charstring(info, glyph_index, &c); if (x0) *x0 = r ? c.min_x : 0; if (y0) *y0 = r ? c.min_y : 0; if (x1) *x1 = r ? c.max_x : 0; if (y1) *y1 = r ? c.max_y : 0; return r ? c.num_vertices : 0; } STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { if (!info->cff.size) return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); else return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); } STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) { stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); if (glyph_index < numOfLongHorMetrics) { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); } else { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); } } static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) { stbtt_uint8 *data = info->data + info->kern; stbtt_uint32 needle, straw; int l, r, m; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; l = 0; r = ttUSHORT(data+10) - 1; needle = glyph1 << 16 | glyph2; while (l <= r) { m = (l + r) >> 1; straw = ttULONG(data+18+(m*6)); // note: unaligned read if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else return ttSHORT(data+22+(m*6)); } return 0; } static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) { stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); switch(coverageFormat) { case 1: { stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); // Binary search. stbtt_int32 l=0, r=glyphCount-1, m; int straw, needle=glyph; while (l <= r) { stbtt_uint8 *glyphArray = coverageTable + 4; stbtt_uint16 glyphID; m = (l + r) >> 1; glyphID = ttUSHORT(glyphArray + 2 * m); straw = glyphID; if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else { return m; } } } break; case 2: { stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); stbtt_uint8 *rangeArray = coverageTable + 4; // Binary search. stbtt_int32 l=0, r=rangeCount-1, m; int strawStart, strawEnd, needle=glyph; while (l <= r) { stbtt_uint8 *rangeRecord; m = (l + r) >> 1; rangeRecord = rangeArray + 6 * m; strawStart = ttUSHORT(rangeRecord); strawEnd = ttUSHORT(rangeRecord + 2); if (needle < strawStart) r = m - 1; else if (needle > strawEnd) l = m + 1; else { stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); return startCoverageIndex + glyph - strawStart; } } } break; default: { // There are no other cases. STBTT_assert(0); } break; } return -1; } static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) { stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); switch(classDefFormat) { case 1: { stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); stbtt_uint8 *classDef1ValueArray = classDefTable + 6; if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); classDefTable = classDef1ValueArray + 2 * glyphCount; } break; case 2: { stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); stbtt_uint8 *classRangeRecords = classDefTable + 4; // Binary search. stbtt_int32 l=0, r=classRangeCount-1, m; int strawStart, strawEnd, needle=glyph; while (l <= r) { stbtt_uint8 *classRangeRecord; m = (l + r) >> 1; classRangeRecord = classRangeRecords + 6 * m; strawStart = ttUSHORT(classRangeRecord); strawEnd = ttUSHORT(classRangeRecord + 2); if (needle < strawStart) r = m - 1; else if (needle > strawEnd) l = m + 1; else return (stbtt_int32)ttUSHORT(classRangeRecord + 4); } classDefTable = classRangeRecords + 6 * classRangeCount; } break; default: { // There are no other cases. STBTT_assert(0); } break; } return -1; } // Define to STBTT_assert(x) if you want to break on unimplemented formats. #define STBTT_GPOS_TODO_assert(x) static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) { stbtt_uint16 lookupListOffset; stbtt_uint8 *lookupList; stbtt_uint16 lookupCount; stbtt_uint8 *data; stbtt_int32 i; if (!info->gpos) return 0; data = info->data + info->gpos; if (ttUSHORT(data+0) != 1) return 0; // Major version 1 if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 lookupListOffset = ttUSHORT(data+8); lookupList = data + lookupListOffset; lookupCount = ttUSHORT(lookupList); for (i=0; i> 1; pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; secondGlyph = ttUSHORT(pairValue); straw = secondGlyph; if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else { stbtt_int16 xAdvance = ttSHORT(pairValue + 2); return xAdvance; } } } break; case 2: { stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); stbtt_uint16 class1Count = ttUSHORT(table + 12); stbtt_uint16 class2Count = ttUSHORT(table + 14); STBTT_assert(glyph1class < class1Count); STBTT_assert(glyph2class < class2Count); // TODO: Support more formats. STBTT_GPOS_TODO_assert(valueFormat1 == 4); if (valueFormat1 != 4) return 0; STBTT_GPOS_TODO_assert(valueFormat2 == 0); if (valueFormat2 != 0) return 0; if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) { stbtt_uint8 *class1Records = table + 16; stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count); stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class); return xAdvance; } } break; default: { // There are no other cases. STBTT_assert(0); break; }; } } break; }; default: // TODO: Implement other stuff. break; } } return 0; } STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) { int xAdvance = 0; if (info->gpos) xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); if (info->kern) xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); return xAdvance; } STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) { if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs return 0; return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); } STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) { stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); } STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) { if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); if (descent) *descent = ttSHORT(info->data+info->hhea + 6); if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); } STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) { int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); if (!tab) return 0; if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); return 1; } STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) { *x0 = ttSHORT(info->data + info->head + 36); *y0 = ttSHORT(info->data + info->head + 38); *x1 = ttSHORT(info->data + info->head + 40); *y1 = ttSHORT(info->data + info->head + 42); } STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) { int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); return (float) height / fheight; } STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) { int unitsPerEm = ttUSHORT(info->data + info->head + 18); return pixels / unitsPerEm; } STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) { STBTT_free(v, info->userdata); } ////////////////////////////////////////////////////////////////////////////// // // antialiasing software rasterizer // 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=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; if (iy0) *iy0 = 0; if (ix1) *ix1 = 0; if (iy1) *iy1 = 0; } else { // move to integral bboxes (treating pixels as little squares, what pixels get touched)? if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); } } STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); } STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); } STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { 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) + sizeof(stbtt__hheap_chunk) + 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; 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; #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 *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); if (!z) return z; // round dx down to avoid overshooting if (dxdy < 0) z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); else 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->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 static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) { // non-zero winding fill int x0=0, w=0; while (e) { if (w == 0) { // if we're currently at zero, we need to record the edge start point x0 = e->x; w += e->direction; } else { int x1 = e->x; w += e->direction; // if we went to zero, we need to draw if (w == 0) { 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 >> STBTT_FIXSHIFT); } else { if (i >= 0) // add antialiasing for x0 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 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); else j = len; // clip for (++i; i < j; ++i) // fill pixels between x0 and x1 scanline[i] = scanline[i] + (stbtt_uint8) max_weight; } } } } e = e->next; } } 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 int s; // vertical subsample index unsigned char scanline_data[512], *scanline; if (result->w > 512) scanline = (unsigned char *) STBTT_malloc(result->w, userdata); else scanline = scanline_data; y = off_y * vsubsample; e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; while (j < result->h) { STBTT_memset(scanline, 0, result->w); for (s=0; s < vsubsample; ++s) { // find center of pixel for this scanline float scan_y = y + 0.5f; stbtt__active_edge **step = &active; // update all active edges; // remove all active edges that terminate before the center of this scanline while (*step) { stbtt__active_edge * z = *step; if (z->ey <= scan_y) { *step = z->next; // delete from list 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 } } // resort the list if needed for(;;) { int changed=0; step = &active; while (*step && (*step)->next) { if ((*step)->x > (*step)->next->x) { stbtt__active_edge *t = *step; stbtt__active_edge *q = t->next; t->next = q->next; q->next = t; *step = q; changed = 1; } step = &(*step)->next; } if (!changed) break; } // 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 = 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; } // now process all active edges in XOR fashion if (active) stbtt__fill_active_edges(scanline, result->w, active, max_weight); ++y; } STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); ++j; } 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 clearly-defined pairs float y0 = y_top; float x1 = (float) (x); float x2 = (float) (x+1); float x3 = xb; float y3 = y_bottom; // x = e->x + e->dx * (y-y_top) // (y-y_top) = (x - e->x) / e->dx // y = (x - e->x) / e->dx + y_top float y1 = (x - x0) / dx + y_top; float 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) { stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0, i; float scanline_data[129], *scanline, *scanline2; STBTT__NOTUSED(vsubsample); 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 #define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) { 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; } } 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 && midn => n; 0 0 */ /* 0n: 0>n => 0; 0 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 { float x,y; } stbtt__point; static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) { 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 n = 0; for (i=0; i < windings; ++i) n += wcount[i]; e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel if (e == 0) return; n = 0; m=0; for (i=0; i < windings; ++i) { stbtt__point *p = pts + m; m += wcount[i]; j = wcount[i]-1; for (k=0; k < wcount[i]; j=k++) { int a=k,b=j; // skip the edge if horizontal if (p[j].y == p[k].y) continue; // add edge from j to k to the list e[n].invert = 0; if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { e[n].invert = 1; a=j,b=k; } e[n].x0 = p[a].x * scale_x + shift_x; e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; e[n].x1 = p[b].x * scale_x + shift_x; e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; ++n; } } // 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_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); STBTT_free(e, userdata); } static void stbtt__add_point(stbtt__point *points, int n, float x, float y) { if (!points) return; // during first pass, it's unallocated points[n].x = x; points[n].y = y; } // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) { // midpoint float mx = (x0 + 2*x1 + x2)/4; float my = (y0 + 2*y1 + y2)/4; // versus directly drawn line float dx = (x0+x2)/2 - mx; float dy = (y0+y2)/2 - my; if (n > 16) // 65536 segments on one curve better be enough! return 1; if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); } else { stbtt__add_point(points, *num_points,x2,y2); *num_points = *num_points+1; } return 1; } static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) { // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough float dx0 = x1-x0; float dy0 = y1-y0; float dx1 = x2-x1; float dy1 = y2-y1; float dx2 = x3-x2; float dy2 = y3-y2; float dx = x3-x0; float dy = y3-y0; float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); float flatness_squared = longlen*longlen-shortlen*shortlen; if (n > 16) // 65536 segments on one curve better be enough! return; if (flatness_squared > objspace_flatness_squared) { float x01 = (x0+x1)/2; float y01 = (y0+y1)/2; float x12 = (x1+x2)/2; float y12 = (y1+y2)/2; float x23 = (x2+x3)/2; float y23 = (y2+y3)/2; float xa = (x01+x12)/2; float ya = (y01+y12)/2; float xb = (x12+x23)/2; float yb = (y12+y23)/2; float mx = (xa+xb)/2; float my = (ya+yb)/2; stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); } else { stbtt__add_point(points, *num_points,x3,y3); *num_points = *num_points+1; } } // returns number of contours static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) { stbtt__point *points=0; int num_points=0; float objspace_flatness_squared = objspace_flatness * objspace_flatness; int i,n=0,start=0, pass; // count how many "moves" there are to get the contour count for (i=0; i < num_verts; ++i) if (vertices[i].type == STBTT_vmove) ++n; *num_contours = n; if (n == 0) return 0; *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); if (*contour_lengths == 0) { *num_contours = 0; return 0; } // make two passes through the points so we don't need to realloc for (pass=0; pass < 2; ++pass) { float x=0,y=0; if (pass == 1) { points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); if (points == NULL) goto error; } num_points = 0; n= -1; for (i=0; i < num_verts; ++i) { switch (vertices[i].type) { case STBTT_vmove: // start the next contour if (n >= 0) (*contour_lengths)[n] = num_points - start; ++n; start = num_points; x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x,y); break; case STBTT_vline: x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x, y); break; case STBTT_vcurve: stbtt__tesselate_curve(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; case STBTT_vcubic: stbtt__tesselate_cubic(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].cx1, vertices[i].cy1, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; } } (*contour_lengths)[n] = num_points - start; } return points; error: STBTT_free(points, userdata); STBTT_free(*contour_lengths, userdata); *contour_lengths = 0; *num_contours = 0; return NULL; } 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) { float scale = scale_x > scale_y ? scale_y : scale_x; int winding_count = 0; int *winding_lengths = NULL; stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); if (windings) { stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); STBTT_free(winding_lengths, userdata); STBTT_free(windings, userdata); } } STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) { STBTT_free(bitmap, userdata); } STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) { int ix0,iy0,ix1,iy1; stbtt__bitmap gbm; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { if (scale_x == 0) { STBTT_free(vertices, info->userdata); return NULL; } scale_y = scale_x; } stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); // now we get the size gbm.w = (ix1 - ix0); gbm.h = (iy1 - iy0); gbm.pixels = NULL; // in case we error if (width ) *width = gbm.w; if (height) *height = gbm.h; if (xoff ) *xoff = ix0; if (yoff ) *yoff = iy0; if (gbm.w && gbm.h) { gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); if (gbm.pixels) { gbm.stride = gbm.w; stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); } } STBTT_free(vertices, info->userdata); return gbm.pixels; } STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); } STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) { int ix0,iy0; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); stbtt__bitmap gbm; stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); gbm.pixels = output; gbm.w = out_w; gbm.h = out_h; gbm.stride = out_stride; if (gbm.w && gbm.h) stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); STBTT_free(vertices, info->userdata); } STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); } STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); } STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) { stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); } STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); } STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); } STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) { stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); } ////////////////////////////////////////////////////////////////////////////// // // bitmap baking // // This is SUPER-CRAPPY packing to keep source code small static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake stbtt_bakedchar *chardata) { 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 x=y=1; bottom_y = 1; scale = stbtt_ScaleForPixelHeight(&f, pixel_height); for (i=0; i < num_chars; ++i) { int advance, lsb, x0,y0,x1,y1,gw,gh; int g = stbtt_FindGlyphIndex(&f, first_char + i); stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); gw = x1-x0; gh = y1-y0; if (x + gw + 1 >= pw) y = bottom_y, x = 1; // advance to next row if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row return -i; STBTT_assert(x+gw < pw); STBTT_assert(y+gh < ph); stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); chardata[i].x0 = (stbtt_int16) x; chardata[i].y0 = (stbtt_int16) y; chardata[i].x1 = (stbtt_int16) (x + gw); chardata[i].y1 = (stbtt_int16) (y + gh); chardata[i].xadvance = scale * advance; chardata[i].xoff = (float) x0; chardata[i].yoff = (float) y0; x = x + gw + 1; if (y+gh+1 > bottom_y) bottom_y = y+gh+1; } return bottom_y; } STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) { float d3d_bias = opengl_fillrule ? 0 : -0.5f; float ipw = 1.0f / pw, iph = 1.0f / ph; const stbtt_bakedchar *b = chardata + char_index; 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; q->x1 = round_x + b->x1 - b->x0 + d3d_bias; q->y1 = round_y + b->y1 - b->y0 + d3d_bias; q->s0 = b->x0 * ipw; q->t0 = b->y0 * iph; q->s1 = b->x1 * ipw; q->t1 = b->y1 * iph; *xpos += b->xadvance; } ////////////////////////////////////////////////////////////////////////////// // // rectangle packing replacement routines if you don't have stb_rect_pack.h // #ifndef STB_RECT_PACK_VERSION typedef int stbrp_coord; //////////////////////////////////////////////////////////////////////////////////// // // // // // COMPILER WARNING ?!?!? // // // // // // if you get a compile warning due to these symbols being defined more than // // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // // // //////////////////////////////////////////////////////////////////////////////////// typedef struct { int width,height; int x,y,bottom_y; } stbrp_context; typedef struct { unsigned char x; } stbrp_node; struct stbrp_rect { stbrp_coord x,y; int id,w,h,was_packed; }; static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) { con->width = pw; con->height = ph; con->x = 0; con->y = 0; con->bottom_y = 0; STBTT__NOTUSED(nodes); STBTT__NOTUSED(num_nodes); } static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) { int i; for (i=0; i < num_rects; ++i) { if (con->x + rects[i].w > con->width) { con->x = 0; con->y = con->bottom_y; } if (con->y + rects[i].h > con->height) break; rects[i].x = con->x; rects[i].y = con->y; rects[i].was_packed = 1; con->x += rects[i].w; if (con->y + rects[i].h > con->bottom_y) con->bottom_y = con->y + rects[i].h; } for ( ; i < num_rects; ++i) rects[i].was_packed = 0; } #endif ////////////////////////////////////////////////////////////////////////////// // // bitmap baking // // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) { stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); int num_nodes = pw - padding; stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); if (context == NULL || nodes == NULL) { if (context != NULL) STBTT_free(context, alloc_context); if (nodes != NULL) STBTT_free(nodes , alloc_context); return 0; } spc->user_allocator_context = alloc_context; spc->width = pw; spc->height = ph; spc->pixels = pixels; spc->pack_info = context; spc->nodes = nodes; spc->padding = padding; spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; spc->h_oversample = 1; spc->v_oversample = 1; stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); if (pixels) STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels return 1; } STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) { STBTT_free(spc->nodes , spc->user_allocator_context); STBTT_free(spc->pack_info, spc->user_allocator_context); } STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) { STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); if (h_oversample <= STBTT_MAX_OVERSAMPLE) spc->h_oversample = h_oversample; if (v_oversample <= STBTT_MAX_OVERSAMPLE) spc->v_oversample = v_oversample; } #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { 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; STBTT_memset(buffer, 0, kernel_width); total = 0; // make kernel_width a constant in common cases so compiler can optimize out the divide switch (kernel_width) { case 2: 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 / 2); } break; case 3: 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 / 3); } break; case 4: 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 / 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]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / kernel_width); } break; } for (; i < w; ++i) { STBTT_assert(pixels[i] == 0); total -= buffer[i & STBTT__OVER_MASK]; pixels[i] = (unsigned char) (total / kernel_width); } pixels += stride_in_bytes; } } static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { 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; STBTT_memset(buffer, 0, kernel_width); total = 0; // make kernel_width a constant in common cases so compiler can optimize out the divide switch (kernel_width) { case 2: 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 / 2); } break; case 3: 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 / 3); } break; case 4: 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 / 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]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); } break; } for (; i < h; ++i) { STBTT_assert(pixels[i*stride_in_bytes] == 0); total -= buffer[i & STBTT__OVER_MASK]; pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); } pixels += 1; } } static float stbtt__oversample_shift(int oversample) { if (!oversample) return 0.0f; // The prefilter is a box filter of width "oversample", // which shifts phase by (oversample - 1)/2 pixels in // oversampled space. We want to shift in the opposite // direction to counter this. return (float)-(oversample - 1) / (2.0f * (float)oversample); } // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { int i,j,k; 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); 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 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; } } return k; } STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph); if (prefilter_x > 1) stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); if (prefilter_y > 1) stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); *sub_x = stbtt__oversample_shift(prefilter_x); *sub_y = stbtt__oversample_shift(prefilter_y); } // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { 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); 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 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 r->x += pad; r->y += pad; r->w -= pad; r->h -= pad; stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); stbtt_GetGlyphBitmapBox(info, glyph, scale * spc->h_oversample, scale * spc->v_oversample, &x0,&y0,&x1,&y1); stbtt_MakeGlyphBitmapSubpixel(info, spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w - spc->h_oversample+1, r->h - spc->v_oversample+1, spc->stride_in_bytes, scale * spc->h_oversample, scale * spc->v_oversample, 0,0, glyph); if (spc->h_oversample > 1) stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w, r->h, spc->stride_in_bytes, spc->h_oversample); if (spc->v_oversample > 1) stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w, r->h, spc->stride_in_bytes, spc->v_oversample); bc->x0 = (stbtt_int16) r->x; bc->y0 = (stbtt_int16) r->y; bc->x1 = (stbtt_int16) (r->x + r->w); bc->y1 = (stbtt_int16) (r->y + r->h); bc->xadvance = scale * advance; bc->xoff = (float) x0 * recip_h + sub_x; bc->yoff = (float) y0 * recip_v + sub_y; bc->xoff2 = (x0 + r->w) * recip_h + sub_x; bc->yoff2 = (y0 + r->h) * recip_v + sub_y; } else { return_value = 0; // if any fail, report failure } ++k; } } // 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, const 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_rect *rects; // flag all characters as NOT packed for (i=0; i < num_ranges; ++i) 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 = ranges[i].chardata_for_range[j].y1 = 0; n = 0; for (i=0; i < num_ranges; ++i) 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); 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, const unsigned char *fontdata, int font_index, float font_size, int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) { stbtt_pack_range 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); } STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) { float ipw = 1.0f / pw, iph = 1.0f / ph; const stbtt_packedchar *b = chardata + char_index; if (align_to_integer) { 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; q->y1 = y + b->yoff2 - b->yoff; } else { q->x0 = *xpos + b->xoff; q->y0 = *ypos + b->yoff; q->x1 = *xpos + b->xoff2; q->y1 = *ypos + b->yoff2; } q->s0 = b->x0 * ipw; q->t0 = b->y0 * iph; q->s1 = b->x1 * ipw; q->t1 = b->y1 * iph; *xpos += b->xadvance; } ////////////////////////////////////////////////////////////////////////////// // // sdf computation // #define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) #define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) { float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; float roperp = orig[1]*ray[0] - orig[0]*ray[1]; float a = q0perp - 2*q1perp + q2perp; float b = q1perp - q0perp; float c = q0perp - roperp; float s0 = 0., s1 = 0.; int num_s = 0; if (a != 0.0) { float discr = b*b - a*c; if (discr > 0.0) { float rcpna = -1 / a; float d = (float) STBTT_sqrt(discr); s0 = (b+d) * rcpna; s1 = (b-d) * rcpna; if (s0 >= 0.0 && s0 <= 1.0) num_s = 1; if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { if (num_s == 0) s0 = s1; ++num_s; } } } else { // 2*b*s + c = 0 // s = -c / (2*b) s0 = c / (-2 * b); if (s0 >= 0.0 && s0 <= 1.0) num_s = 1; } if (num_s == 0) return 0; else { float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; float q0d = q0[0]*rayn_x + q0[1]*rayn_y; float q1d = q1[0]*rayn_x + q1[1]*rayn_y; float q2d = q2[0]*rayn_x + q2[1]*rayn_y; float rod = orig[0]*rayn_x + orig[1]*rayn_y; float q10d = q1d - q0d; float q20d = q2d - q0d; float q0rd = q0d - rod; hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; hits[0][1] = a*s0+b; if (num_s > 1) { hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; hits[1][1] = a*s1+b; return 2; } else { return 1; } } } static int equal(float *a, float *b) { return (a[0] == b[0] && a[1] == b[1]); } static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) { int i; float orig[2], ray[2] = { 1, 0 }; float y_frac; int winding = 0; orig[0] = x; orig[1] = y; // make sure y never passes through a vertex of the shape y_frac = (float) STBTT_fmod(y, 1.0f); if (y_frac < 0.01f) y += 0.01f; else if (y_frac > 0.99f) y -= 0.01f; orig[1] = y; // test a ray from (-infinity,y) to (x,y) for (i=0; i < nverts; ++i) { if (verts[i].type == STBTT_vline) { int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; if (x_inter < x) winding += (y0 < y1) ? 1 : -1; } } if (verts[i].type == STBTT_vcurve) { int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); int by = STBTT_max(y0,STBTT_max(y1,y2)); if (y > ay && y < by && x > ax) { float q0[2],q1[2],q2[2]; float hits[2][2]; q0[0] = (float)x0; q0[1] = (float)y0; q1[0] = (float)x1; q1[1] = (float)y1; q2[0] = (float)x2; q2[1] = (float)y2; if (equal(q0,q1) || equal(q1,q2)) { x0 = (int)verts[i-1].x; y0 = (int)verts[i-1].y; x1 = (int)verts[i ].x; y1 = (int)verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; if (x_inter < x) winding += (y0 < y1) ? 1 : -1; } } else { int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); if (num_hits >= 1) if (hits[0][0] < 0) winding += (hits[0][1] < 0 ? -1 : 1); if (num_hits >= 2) if (hits[1][0] < 0) winding += (hits[1][1] < 0 ? -1 : 1); } } } } return winding; } static float stbtt__cuberoot( float x ) { if (x<0) return -(float) STBTT_pow(-x,1.0f/3.0f); else return (float) STBTT_pow( x,1.0f/3.0f); } // x^3 + c*x^2 + b*x + a = 0 static int stbtt__solve_cubic(float a, float b, float c, float* r) { float s = -a / 3; float p = b - a*a / 3; float q = a * (2*a*a - 9*b) / 27 + c; float p3 = p*p*p; float d = q*q + 4*p3 / 27; if (d >= 0) { float z = (float) STBTT_sqrt(d); float u = (-q + z) / 2; float v = (-q - z) / 2; u = stbtt__cuberoot(u); v = stbtt__cuberoot(v); r[0] = s + u + v; return 1; } else { float u = (float) STBTT_sqrt(-p/3); float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative float m = (float) STBTT_cos(v); float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; r[0] = s + u * 2 * m; r[1] = s - u * (m + n); r[2] = s - u * (m - n); //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); return 3; } } STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) { float scale_x = scale, scale_y = scale; int ix0,iy0,ix1,iy1; int w,h; unsigned char *data; // if one scale is 0, use same scale for both if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { if (scale_x == 0) return NULL; // if both scales are 0, return NULL scale_y = scale_x; } stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); // if empty, return NULL if (ix0 == ix1 || iy0 == iy1) return NULL; ix0 -= padding; iy0 -= padding; ix1 += padding; iy1 += padding; w = (ix1 - ix0); h = (iy1 - iy0); if (width ) *width = w; if (height) *height = h; if (xoff ) *xoff = ix0; if (yoff ) *yoff = iy0; // invert for y-downwards bitmaps scale_y = -scale_y; { int x,y,i,j; float *precompute; stbtt_vertex *verts; int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); data = (unsigned char *) STBTT_malloc(w * h, info->userdata); precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); for (i=0,j=num_verts-1; i < num_verts; j=i++) { if (verts[i].type == STBTT_vline) { float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float len2 = bx*bx + by*by; if (len2 != 0.0f) precompute[i] = 1.0f / (bx*bx + by*by); else precompute[i] = 0.0f; } else precompute[i] = 0.0f; } for (y=iy0; y < iy1; ++y) { for (x=ix0; x < ix1; ++x) { float val; float min_dist = 999999.0f; float sx = (float) x + 0.5f; float sy = (float) y + 0.5f; float x_gspace = (sx / scale_x); float y_gspace = (sy / scale_y); int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path for (i=0; i < num_verts; ++i) { float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; // check against every point here rather than inside line/curve primitives -- @TODO: wrong if multiple 'moves' in a row produce a garbage point, and given culling, probably more efficient to do within line/curve float dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); if (dist2 < min_dist*min_dist) min_dist = (float) STBTT_sqrt(dist2); if (verts[i].type == STBTT_vline) { float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; // coarse culling against bbox //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) float dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; STBTT_assert(i != 0); if (dist < min_dist) { // check position along line // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) float dx = x1-x0, dy = y1-y0; float px = x0-sx, py = y0-sy; // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve float t = -(px*dx + py*dy) / (dx*dx + dy*dy); if (t >= 0.0f && t <= 1.0f) min_dist = dist; } } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); // coarse culling against bbox to avoid computing cubic unnecessarily if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { int num=0; float ax = x1-x0, ay = y1-y0; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float mx = x0 - sx, my = y0 - sy; float res[3],px,py,t,it; float a_inv = precompute[i]; if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula float a = 3*(ax*bx + ay*by); float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); float c = mx*ax+my*ay; if (a == 0.0) { // if a is 0, it's linear if (b != 0.0) { res[num++] = -c/b; } } else { float discriminant = b*b - 4*a*c; if (discriminant < 0) num = 0; else { float root = (float) STBTT_sqrt(discriminant); res[0] = (-b - root)/(2*a); res[1] = (-b + root)/(2*a); num = 2; // don't bother distinguishing 1-solution case, as code below will still work } } } else { float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; float d = (mx*ax+my*ay) * a_inv; num = stbtt__solve_cubic(b, c, d, res); } if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { t = res[0], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { t = res[1], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { t = res[2], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } } } } if (winding == 0) min_dist = -min_dist; // if outside the shape, value is negative val = onedge_value + pixel_dist_scale * min_dist; if (val < 0) val = 0; else if (val > 255) val = 255; data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; } } STBTT_free(precompute, info->userdata); STBTT_free(verts, info->userdata); } return data; } STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); } STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) { STBTT_free(bitmap, userdata); } ////////////////////////////////////////////////////////////////////////////// // // font name matching -- recommended not to use this // // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) { stbtt_int32 i=0; // convert utf16 to utf8 and compare the results while converting while (len2) { stbtt_uint16 ch = s2[0]*256 + s2[1]; if (ch < 0x80) { if (i >= len1) return -1; if (s1[i++] != ch) return -1; } else if (ch < 0x800) { if (i+1 >= len1) return -1; if (s1[i++] != 0xc0 + (ch >> 6)) return -1; if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; } else if (ch >= 0xd800 && ch < 0xdc00) { stbtt_uint32 c; stbtt_uint16 ch2 = s2[2]*256 + s2[3]; if (i+3 >= len1) return -1; c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; if (s1[i++] != 0xf0 + (c >> 18)) return -1; if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; s2 += 2; // plus another 2 below len2 -= 2; } else if (ch >= 0xdc00 && ch < 0xe000) { return -1; } else { if (i+2 >= len1) return -1; if (s1[i++] != 0xe0 + (ch >> 12)) return -1; if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; } s2 += 2; len2 -= 2; } return i; } static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) { return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); } // returns results in whatever encoding you request... but note that 2-byte encodings // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) { stbtt_int32 i,count,stringOffset; stbtt_uint8 *fc = font->data; stbtt_uint32 offset = font->fontstart; stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); if (!nm) return NULL; count = ttUSHORT(fc+nm+2); stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { stbtt_uint32 loc = nm + 6 + 12 * i; if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { *length = ttUSHORT(fc+loc+8); return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); } } return NULL; } static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) { stbtt_int32 i; stbtt_int32 count = ttUSHORT(fc+nm+2); stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { stbtt_uint32 loc = nm + 6 + 12 * i; stbtt_int32 id = ttUSHORT(fc+loc+6); if (id == target_id) { // find the encoding stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); // is this a Unicode encoding? if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { stbtt_int32 slen = ttUSHORT(fc+loc+8); stbtt_int32 off = ttUSHORT(fc+loc+10); // check if there's a prefix match stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); if (matchlen >= 0) { // check for target_id+1 immediately following, with same encoding & language if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { slen = ttUSHORT(fc+loc+12+8); off = ttUSHORT(fc+loc+12+10); if (slen == 0) { if (matchlen == nlen) return 1; } else if (matchlen < nlen && name[matchlen] == ' ') { ++matchlen; if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) return 1; } } else { // if nothing immediately following if (matchlen == nlen) return 1; } } } // @TODO handle other encodings } } return 0; } static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) { stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); stbtt_uint32 nm,hd; if (!stbtt__isfont(fc+offset)) return 0; // check italics/bold/underline flags in macStyle... if (flags) { hd = stbtt__find_table(fc, offset, "head"); if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; } nm = stbtt__find_table(fc, offset, "name"); if (!nm) return 0; if (flags) { // if we checked the macStyle flags, then just check the family and ignore the subfamily if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; } else { if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; } return 0; } static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) { stbtt_int32 i; for (i=0;;++i) { stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); if (off < 0) return off; if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) return off; } } #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, float pixel_height, unsigned char *pixels, int pw, int ph, int first_char, int num_chars, stbtt_bakedchar *chardata) { return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); } STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) { return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); } STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) { return stbtt_GetNumberOfFonts_internal((unsigned char *) data); } STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) { return stbtt_InitFont_internal(info, (unsigned char *) data, offset); } STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) { return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); } STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) { return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); } #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic pop #endif #endif // STB_TRUETYPE_IMPLEMENTATION // FULL VERSION HISTORY // // 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod // 1.18 (2018-01-29) add missing function // 1.17 (2017-07-23) make more arguments const; doc fix // 1.16 (2017-07-12) SDF support // 1.15 (2017-03-03) make more arguments const // 1.14 (2017-01-16) num-fonts-in-TTC function // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual // 1.11 (2016-04-02) fix unused-variable warning // 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 // /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */ ================================================ FILE: ui/index.html ================================================ GPU Top ================================================ FILE: ui/meson.build ================================================ imgui_src = [ 'imgui/imgui.cpp', 'imgui/imgui_demo.cpp', 'imgui/imgui_draw.cpp', ] imgui_inc = include_directories('imgui') imgui_deps = [] ui_src = [ 'gputop-ui-main.cpp', 'gputop-ui-multilines.cpp', 'gputop-ui-piechart.cpp', 'gputop-ui-plots.cpp', 'gputop-ui-timeline.cpp', 'gputop-ui-topology.cpp', 'gputop-ui-utils.cpp', ] ui_inc = include_directories('.', 'imgui') ui_flags = [ '-Wno-invalid-offsetof' ] imgui = static_library('imgui', imgui_src, include_directories : imgui_inc, cpp_args : ['-Wno-unused-parameter', '-Wno-unused-function', '-Wno-sign-compare'], dependencies : imgui_deps) if build_webui ui_src += [ 'imgui/imgui_impl_sdl_gles2.cpp', 'gputop-emscripten-network.c', ] executable('gputop-ui.js', ui_src, include_directories : ui_inc, cpp_args : ui_flags, link_with : imgui, dependencies : gputop_client_dep, install : true) else if build_native_ui glfw_ui_src = ui_src + [ 'imgui/imgui_impl_glfw_gl3.cpp', 'gputop-uv-network.c', ] glfw_ui_flags = ui_flags + [ '-DGPUTOP_UI_GLFW', '-DGLFW_EXPOSE_NATIVE_EGL', ] glfw_ui_deps = [ dependency('glfw3'), dependency('epoxy'), libuv_dep, wslay_dep, dependency('threads'), ] x11_dep = dependency('x11', required : false) if x11_dep.found() glfw_ui_flags += [ '-DGLFW_EXPOSE_NATIVE_X11', ] glfw_ui_deps += x11_dep endif wayland_dep = dependency('wayland-client', required : false) if wayland_dep.found() glfw_ui_flags += [ '-DGLFW_EXPOSE_NATIVE_WAYLAND', ] glfw_ui_deps += wayland_dep endif executable('gputop-ui', glfw_ui_src, include_directories : ui_inc, cpp_args : glfw_ui_flags, link_with : imgui, dependencies : [gputop_client_dep, glfw_ui_deps], install : true) endif if get_option('native_ui_gtk') gtk_dep = dependency('gtk+-3.0', version : '>= 3.18.0') cogl_dep = dependency('cogl-2.0-experimental') libsoup_dep = dependency('libsoup-2.4', version : '>= 2.60.3') gtk_ui_src = ui_src + [ 'imgui/imgui_impl_gtk3_cogl.cpp', 'gputop-soup-network.c', ] gtk_ui_flags = ui_flags + [ '-DGPUTOP_UI_GTK', ] gtk_ui_deps = [ dependency('threads'), gtk_dep, cogl_dep, libsoup_dep, ] executable('gputop-ui-gtk', gtk_ui_src, include_directories : ui_inc, cpp_args : gtk_ui_flags, link_with : imgui, dependencies : [gputop_client_dep, gtk_ui_deps], install : true) endif endif ================================================ FILE: utils/gputop-configs.c ================================================ /* * GPU Top * * Copyright (C) 2018 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "gputop-oa-metrics.h" static bool gputop_read_file_uint64(const char *file, uint64_t *value) { char buf[32]; int fd, n; fd = open(file, 0); if (fd < 0) return false; n = read(fd, buf, sizeof (buf) - 1); close(fd); if (n < 0) return false; buf[n] = '\0'; *value = strtoull(buf, 0, 0); return true; } static uint32_t read_device_param(const char *stem, int id, const char *param) { char *name; int ret = asprintf(&name, "/sys/class/drm/%s%u/device/%s", stem, id, param); uint64_t value; bool success; assert(ret != -1); success = gputop_read_file_uint64(name, &value); free(name); return success ? value : 0; } static int find_intel_render_node(void) { for (int i = 128; i < (128 + 16); i++) { if (read_device_param("renderD", i, "vendor") == 0x8086) return i; } return -1; } static int open_render_node(uint32_t *devid) { char *name; int ret; int fd; int render = find_intel_render_node(); if (render < 0) return -1; ret = asprintf(&name, "/dev/dri/renderD%u", render); assert(ret != -1); *devid = read_device_param("renderD", render, "device"); fd = open(name, O_RDWR); free(name); return fd; } static int get_card_for_fd(int fd) { struct stat sb; int mjr, mnr; char buffer[128]; DIR *drm_dir; struct dirent *entry; int retval = -1; if (fstat(fd, &sb)) { fprintf(stderr, "Failed to stat DRM fd\n"); return -1; } mjr = major(sb.st_rdev); mnr = minor(sb.st_rdev); snprintf(buffer, sizeof(buffer), "/sys/dev/char/%d:%d/device/drm", mjr, mnr); drm_dir = opendir(buffer); assert(drm_dir != NULL); while ((entry = readdir(drm_dir))) { if (entry->d_type == DT_DIR && strncmp(entry->d_name, "card", 4) == 0) { retval = strtoull(entry->d_name + 4, NULL, 10); break; } } closedir(drm_dir); return retval; } static int perf_ioctl(int fd, unsigned long request, void *arg) { int ret; do { ret = ioctl(fd, request, arg); } while (ret == -1 && (errno == EINTR || errno == EAGAIN)); return ret; } static const char * metric_name(struct gputop_gen *gen, const char *hw_config_guid) { struct hash_entry *entry = _mesa_hash_table_search(gen->metric_sets_map, hw_config_guid); if (!entry) return "Unknown"; struct gputop_metric_set *metric_set = entry->data; return metric_set->symbol_name; } static void usage(void) { printf("Usage: gputop-configs [options]\n" "\n" " --purge, -p Purge configurations from the kernel\n" " --list, -l List configurations from the kernel\n"); } int main(int argc, char *argv[]) { char metrics_path[128]; DIR *metrics_dir; struct dirent *entry; int drm_fd, drm_card; int opt; bool purge = false; const struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"list", no_argument, 0, 'l'}, {"purge", no_argument, 0, 'p'}, {0, 0, 0, 0} }; struct gputop_gen *gen; struct gen_device_info devinfo; uint32_t devid = 0; while ((opt = getopt_long(argc, argv, "hlp", long_options, NULL)) != -1) { switch (opt) { case 'h': usage(); return EXIT_SUCCESS; case 'l': break; case 'p': purge = true; break; default: fprintf(stderr, "Internal error: " "unexpected getopt value: %d\n", opt); usage(); return EXIT_FAILURE; } } drm_fd = open_render_node(&devid); drm_card = get_card_for_fd(drm_fd); fprintf(stdout, "Found device id=0x%x\n", devid); if (!gen_get_device_info_from_pci_id(devid, &devinfo)) { fprintf(stderr, "No device info found.\n"); return EXIT_FAILURE; } fprintf(stdout, "Device gen=%i gt=%i\n", devinfo.gen, devinfo.gt); gen = gputop_gen_for_devinfo(&devinfo); if (!gen) { fprintf(stderr, "No metric sets found for device.\n"); return EXIT_FAILURE; } snprintf(metrics_path, sizeof(metrics_path), "/sys/class/drm/card%d/metrics", drm_card); metrics_dir = opendir(metrics_path); if (!metrics_dir) return EXIT_FAILURE; fprintf(stdout, "Looking at metrics in %s\n", metrics_path); while ((entry = readdir(metrics_dir))) { char metric_id_path[sizeof(metrics_path) + sizeof(entry->d_name) + 4]; uint64_t metric_id; if (entry->d_type != DT_DIR) continue; snprintf(metric_id_path, sizeof(metric_id_path), "%s/%s/id", metrics_path, entry->d_name); if (!gputop_read_file_uint64(metric_id_path, &metric_id)) continue; if (purge) { if (perf_ioctl(drm_fd, DRM_IOCTL_I915_PERF_REMOVE_CONFIG, &metric_id) == 0) fprintf(stdout, "\tRemoved config %s id=%03" PRIu64 " name=%s\n", entry->d_name, metric_id, metric_name(gen, entry->d_name)); else fprintf(stdout, "\tFailed to remove config %s id=%03" PRIu64 " name=%s\n", entry->d_name, metric_id, metric_name(gen, entry->d_name)); } else { fprintf(stdout, "\tConfig %s id=%03" PRIu64 " name=%s\n", entry->d_name, metric_id, metric_name(gen, entry->d_name)); } } closedir(metrics_dir); close(drm_fd); return EXIT_SUCCESS; } ================================================ FILE: utils/meson.build ================================================ executable('gputop-configs', [ 'gputop-configs.c' ], c_args: [ '-D_GNU_SOURCE' ], dependencies: [mesa_dep, gputop_client_dep], install: true) ================================================ FILE: wrapper/gputop-uv-network.c ================================================ /* * GPU Top * * Copyright (C) 2018 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "gputop-network.h" #include #include #include #include #include "util/macros.h" struct _gputop_connection_t { bool open; uv_tcp_t tcp_handle; uv_connect_t connect_req; uv_write_t write_header_req; const uv_buf_t *read_buf; size_t iread, nread; uv_check_t check_handle; wslay_event_context_ptr wslay_ctx; gputop_on_ready_cb_t ready_cb; gputop_on_data_cb_t data_cb; gputop_on_close_cb_t close_cb; void *user_data; char http_client_header[1024]; char http_server_header[64 * 1024]; }; static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; static int mod_table[] = {0, 2, 1}; static void base64_encode(const uint8_t *data_in, size_t input_length, uint8_t *data_out) { size_t output_length = 4 * ((input_length + 2) / 3); for (int i = 0, j = 0; i < input_length;) { uint32_t octet_a = i < input_length ? (unsigned char)data_in[i++] : 0; uint32_t octet_b = i < input_length ? (unsigned char)data_in[i++] : 0; uint32_t octet_c = i < input_length ? (unsigned char)data_in[i++] : 0; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; data_out[j++] = encoding_table[(triple >> 3 * 6) & 0x3F]; data_out[j++] = encoding_table[(triple >> 2 * 6) & 0x3F]; data_out[j++] = encoding_table[(triple >> 1 * 6) & 0x3F]; data_out[j++] = encoding_table[(triple >> 0 * 6) & 0x3F]; } for (int i = 0; i < mod_table[input_length % 3]; i++) data_out[output_length - 1 - i] = '='; data_out[output_length] = '\0'; } static void on_close_cb(uv_handle_t *handle) { gputop_connection_t *conn = handle->data; wslay_event_context_free(conn->wslay_ctx); free(conn); } static void gputop_connection_end(gputop_connection_t *conn, const char *error) { conn->close_cb(conn, error, conn->user_data); uv_read_stop((uv_stream_t *) &conn->tcp_handle); uv_check_stop(&conn->check_handle); uv_close((uv_handle_t *) &conn->tcp_handle, on_close_cb); } static int on_wslay_genmask_cb(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) { for (size_t i = 0; i < len; i++) buf[i] = rand() & 0xff; return 0; } static void on_wslay_msg_recv_cb(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) { gputop_connection_t *conn = user_data; if (arg->opcode == WSLAY_CONNECTION_CLOSE) { gputop_connection_end(conn, NULL); return; } conn->data_cb(conn, arg->msg, arg->msg_length, conn->user_data); } static ssize_t on_wslay_recv_cb(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, int flags, void *user_data) { gputop_connection_t *conn = user_data; int l; if (!conn->read_buf || conn->iread >= conn->nread) { wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK); return -1; } l = MIN2(len, conn->nread - conn->iread); memcpy(buf, &conn->read_buf->base[conn->iread], l); conn->iread += l; return l; } static ssize_t on_wslay_send_cb(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) { gputop_connection_t *conn = user_data; const uv_buf_t buf = uv_buf_init((char *)data, len); return uv_try_write((uv_stream_t *) &conn->tcp_handle, &buf, 1); } static void on_uv_read_alloc_cb(uv_handle_t *handle, size_t size, uv_buf_t *buf) { gputop_connection_t *conn = handle->data; buf->base = conn->http_server_header; buf->len = sizeof(conn->http_server_header); } static void on_uv_read_cb(uv_stream_t *handle, ssize_t nread, const uv_buf_t *buf) { gputop_connection_t *conn = handle->data; if (!conn->open) { conn->open = true; conn->ready_cb(conn, conn->user_data); return; } if (nread == UV_EOF) { gputop_connection_end(conn, NULL); return; } conn->read_buf = buf; conn->iread = 0; conn->nread = nread; wslay_event_recv(conn->wslay_ctx); conn->read_buf = NULL; conn->iread = 0; } static void on_uv_connect_cb(uv_connect_t* req, int status) { gputop_connection_t *conn = req->handle->data; uv_buf_t buf; if (status != 0) { gputop_connection_end(conn, uv_err_name(status)); return; } uv_read_start((uv_stream_t *) &conn->tcp_handle, on_uv_read_alloc_cb, on_uv_read_cb); buf = uv_buf_init(conn->http_client_header, strlen(conn->http_client_header)); uv_write(&conn->write_header_req, (uv_stream_t *) &conn->tcp_handle, &buf, 1, NULL); } static void on_check_cb(uv_check_t* handle) { gputop_connection_t *conn = handle->data; if (wslay_event_want_write(conn->wslay_ctx)) { if (wslay_event_send(conn->wslay_ctx) != 0) gputop_connection_close(conn); } if (wslay_event_want_read(conn->wslay_ctx)) { if (wslay_event_recv(conn->wslay_ctx) != 0) gputop_connection_close(conn); } } gputop_connection_t * gputop_connect(const char *host, int port, gputop_on_ready_cb_t ready_cb, gputop_on_data_cb_t data_cb, gputop_on_close_cb_t close_cb, void *user_data) { gputop_connection_t *conn = calloc(1, sizeof(gputop_connection_t)); uint8_t ws_key[16]; uint8_t ws_key_b64[100]; struct wslay_event_callbacks callbacks = { on_wslay_recv_cb, on_wslay_send_cb, on_wslay_genmask_cb, NULL, NULL, NULL, on_wslay_msg_recv_cb, }; uv_getaddrinfo_t req; int i; conn->ready_cb = ready_cb; conn->data_cb = data_cb; conn->close_cb = close_cb; wslay_event_context_client_init(&conn->wslay_ctx, &callbacks, conn); uv_tcp_init(uv_default_loop(), &conn->tcp_handle); conn->tcp_handle.data = conn; //uv_stream_set_blocking((uv_stream_t *)&conn->tcp_handle, 0); if (uv_getaddrinfo(uv_default_loop(), &req, NULL, host, NULL, NULL) == 0) { union { struct sockaddr addr; struct sockaddr_in addr4; struct sockaddr_in6 addr6; } s; memcpy(&s.addr6, req.addrinfo->ai_addr, req.addrinfo->ai_addrlen); if (req.addrinfo->ai_family == AF_INET6) { s.addr6.sin6_port = htons(port); } else { s.addr4.sin_port = htons(port); } uv_tcp_connect(&conn->connect_req, &conn->tcp_handle, &s.addr, on_uv_connect_cb); uv_freeaddrinfo(req.addrinfo); } else { struct sockaddr_in addr; uv_ip4_addr("127.0.0.1", port, &addr); uv_tcp_connect(&conn->connect_req, &conn->tcp_handle, (const struct sockaddr*) &addr, on_uv_connect_cb); } for (i = 0; i < ARRAY_SIZE(ws_key); i++) ws_key[i] = rand() % 0xff; base64_encode(ws_key, sizeof(ws_key), ws_key_b64); snprintf(conn->http_client_header, sizeof(conn->http_client_header), "GET /gputop HTTP/1.1\r\n" "Host: %s:%u\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Key: %s\r\n" "Sec-WebSocket-Version: 13\r\n\r\n", host, port, ws_key_b64); uv_check_init(uv_default_loop(), &conn->check_handle); conn->check_handle.data = conn; uv_check_start(&conn->check_handle, on_check_cb); return conn; } void gputop_connection_send(gputop_connection_t *conn, const void *data, size_t len) { struct wslay_event_msg msg; assert(conn != NULL); assert(gputop_connection_connected(conn)); assert(data != NULL && len > 0); msg.opcode = WSLAY_BINARY_FRAME; msg.msg = data; msg.msg_length = len; wslay_event_queue_msg(conn->wslay_ctx, &msg); wslay_event_send(conn->wslay_ctx); } void gputop_connection_close(gputop_connection_t *conn) { assert(conn != NULL); wslay_event_queue_close(conn->wslay_ctx, WSLAY_CODE_NORMAL_CLOSURE, NULL, 0); wslay_event_send(conn->wslay_ctx); } bool gputop_connection_connected(gputop_connection_t *conn) { assert(conn != NULL); return conn->open; } ================================================ FILE: wrapper/gputop-wrapper-main.c ================================================ /* * GPU Top * * Copyright (C) 2017 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include "gputop-client-context.h" #include "gputop-network.h" #include const struct gputop_metric_set_counter timestamp_counter = { .metric_set = NULL, .name = "Timestamp", .symbol_name = "Timestamp", .desc = "OA unit timestamp", .type = GPUTOP_PERFQUERY_COUNTER_TIMESTAMP, .data_type = GPUTOP_PERFQUERY_COUNTER_DATA_UINT64, .units = GPUTOP_PERFQUERY_COUNTER_UNITS_NS, }; static struct { struct gputop_client_context ctx; const char *metric_name; struct { char *symbol_name; const struct gputop_metric_set_counter *counter; int width; } *metric_columns; int n_metric_columns; bool all_columns; bool human_units; bool print_headers; bool print_maximums; FILE *wrapper_output; int n_accumulations; struct gputop_accumulated_samples *last_samples; int child_process_pid; char **child_process_args; const char *child_process_output_file; uint32_t n_child_process_args; uv_timer_t child_process_timer_handle; bool child_exited; uint32_t max_idle_child_time_ms; struct hash_table *process_ids; } context; static void comment(const char *format, ...) { va_list ap; va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); } static void output(const char *format, ...) { va_list ap; va_start(ap, format); vfprintf(context.wrapper_output, format, ap); va_end(ap); } void gputop_cr_console_log(const char *format, ...) { va_list ap; va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); fprintf(stderr, "\n"); } static int unit_to_width(gputop_counter_units_t unit) { switch (unit) { case GPUTOP_PERFQUERY_COUNTER_UNITS_BYTES: return 8; case GPUTOP_PERFQUERY_COUNTER_UNITS_HZ: return 8; case GPUTOP_PERFQUERY_COUNTER_UNITS_NS: return 12; case GPUTOP_PERFQUERY_COUNTER_UNITS_US: return 8; case GPUTOP_PERFQUERY_COUNTER_UNITS_PIXELS: case GPUTOP_PERFQUERY_COUNTER_UNITS_TEXELS: return 8 + 2; case GPUTOP_PERFQUERY_COUNTER_UNITS_THREADS: return 8; case GPUTOP_PERFQUERY_COUNTER_UNITS_PERCENT: return 6; case GPUTOP_PERFQUERY_COUNTER_UNITS_MESSAGES: case GPUTOP_PERFQUERY_COUNTER_UNITS_NUMBER: case GPUTOP_PERFQUERY_COUNTER_UNITS_CYCLES: case GPUTOP_PERFQUERY_COUNTER_UNITS_EVENTS: case GPUTOP_PERFQUERY_COUNTER_UNITS_UTILIZATION: case GPUTOP_PERFQUERY_COUNTER_UNITS_EU_SENDS_TO_L3_CACHE_LINES: case GPUTOP_PERFQUERY_COUNTER_UNITS_EU_ATOMIC_REQUESTS_TO_L3_CACHE_LINES: case GPUTOP_PERFQUERY_COUNTER_UNITS_EU_REQUESTS_TO_L3_CACHE_LINES: case GPUTOP_PERFQUERY_COUNTER_UNITS_EU_BYTES_PER_L3_CACHE_LINE: return 8 + 2; default: assert(!"Missing case"); return 0; } } static const char *unit_to_string(gputop_counter_units_t unit) { switch (unit) { case GPUTOP_PERFQUERY_COUNTER_UNITS_BYTES: return "B"; case GPUTOP_PERFQUERY_COUNTER_UNITS_HZ: return "Hz"; case GPUTOP_PERFQUERY_COUNTER_UNITS_NS: return "ns"; case GPUTOP_PERFQUERY_COUNTER_UNITS_US: return "us"; case GPUTOP_PERFQUERY_COUNTER_UNITS_PIXELS: return "pixels"; case GPUTOP_PERFQUERY_COUNTER_UNITS_TEXELS: return "texels"; case GPUTOP_PERFQUERY_COUNTER_UNITS_THREADS: return "threads"; case GPUTOP_PERFQUERY_COUNTER_UNITS_PERCENT: return "%"; case GPUTOP_PERFQUERY_COUNTER_UNITS_MESSAGES: return "messages/s"; case GPUTOP_PERFQUERY_COUNTER_UNITS_NUMBER: return "/s"; case GPUTOP_PERFQUERY_COUNTER_UNITS_CYCLES: return "cycles/s"; case GPUTOP_PERFQUERY_COUNTER_UNITS_EVENTS: return "events/s"; case GPUTOP_PERFQUERY_COUNTER_UNITS_UTILIZATION: return "utilization"; case GPUTOP_PERFQUERY_COUNTER_UNITS_EU_SENDS_TO_L3_CACHE_LINES: return "sends-to-L3-CL"; case GPUTOP_PERFQUERY_COUNTER_UNITS_EU_ATOMIC_REQUESTS_TO_L3_CACHE_LINES: return "atomics-to-L3-CL"; case GPUTOP_PERFQUERY_COUNTER_UNITS_EU_REQUESTS_TO_L3_CACHE_LINES: return "requests-to-L3-CL"; case GPUTOP_PERFQUERY_COUNTER_UNITS_EU_BYTES_PER_L3_CACHE_LINE: return "bytes-per-L3-CL"; default: assert(!"Missing case"); return 0; } } static void quit(void) { gputop_client_context_stop_sampling(&context.ctx); gputop_connection_close(context.ctx.connection); } static void start_child_process(void) { int i, fd_out; if (context.ctx.devinfo.gen < 8) { comment("Process monitoring not supported in Haswell\n"); quit(); return; } context.process_ids = _mesa_hash_table_create(NULL, _mesa_hash_pointer, _mesa_key_pointer_equal); context.child_process_pid = fork(); switch (context.child_process_pid) { case 0: close(1); fd_out = open(context.child_process_output_file, O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if (fd_out == -1) { comment("Cannot create output file '%s': %s\n", context.child_process_output_file, strerror(errno)); exit(EXIT_FAILURE); } if (dup2(fd_out, 1) == -1) { comment("Error redirecting output stream: %s\n", strerror(errno)); exit(EXIT_FAILURE); } execvp(context.child_process_args[0], context.child_process_args); break; case -1: comment("Cannot start child process: %s\n", strerror(errno)); quit(); break; default: comment("Monitoring pid=%u: ", context.child_process_pid); for (i = 0; i < context.n_child_process_args; i++) comment("%s ", context.child_process_args[i]); comment("\n"); break; } } static void on_ctrl_c(uv_signal_t* handle, int signum) { quit(); } static void on_child_timer(uv_timer_t* handle) { uv_timer_stop(&context.child_process_timer_handle); quit(); } static void on_child_process_exit(uv_signal_t* handle, int signum) { /* Given it another aggregation period and quit. */ comment("Child exited.\n"); context.child_exited = true; uv_timer_init(uv_default_loop(), &context.child_process_timer_handle); uv_timer_start(&context.child_process_timer_handle, on_child_timer, MAX2(context.max_idle_child_time_ms, context.ctx.oa_aggregation_period_ns / 1000000ULL), 0); } static void print_system_info(void) { const struct gputop_devinfo *devinfo = &context.ctx.devinfo; char temp[80]; comment("System info:\n"); comment("\tKernel release: %s\n", context.ctx.features->features->kernel_release); comment("\tKernel build: %s\n", context.ctx.features->features->kernel_build); comment("CPU info:\n"); comment("\tCPU model: %s\n", context.ctx.features->features->cpu_model); comment("\tCPU cores: %i\n", context.ctx.features->features->n_cpus); comment("GPU info:\n"); comment("\tGT name: %s (Gen %u, PCI 0x%x)\n", devinfo->prettyname, devinfo->gen, devinfo->devid); comment("\tTopology: %llu threads, %llu EUs, %llu slices, %llu subslices\n", devinfo->eu_threads_count, devinfo->n_eus, devinfo->n_eu_slices, devinfo->n_eu_sub_slices); comment("\tGT frequency range: %.1fMHz / %.1fMHz\n", (double) devinfo->gt_min_freq / 1000000.0f, (double) devinfo->gt_max_freq / 1000000.0f); comment("\tCS timestamp frequency: %lu Hz / %.2f ns\n", devinfo->timestamp_frequency, 1000000000.0f / devinfo->timestamp_frequency); comment("OA info:\n"); comment("\tOA Hardware Sampling Exponent: %u\n", gputop_time_to_oa_exponent(&context.ctx.devinfo, context.ctx.oa_aggregation_period_ns)); gputop_client_pretty_print_value(GPUTOP_PERFQUERY_COUNTER_UNITS_NS, gputop_oa_exponent_to_period_ns(&context.ctx.devinfo, gputop_time_to_oa_exponent(&context.ctx.devinfo, context.ctx.oa_aggregation_period_ns)), temp, sizeof(temp)); comment("\tOA Hardware Period: %u ns / %s\n", gputop_oa_exponent_to_period_ns(&context.ctx.devinfo, gputop_time_to_oa_exponent(&context.ctx.devinfo, context.ctx.oa_aggregation_period_ns)), temp); } static void print_metrics(void) { int max_name_length = 0; list_for_each_entry(struct gputop_metric_set, metric_set, &context.ctx.gen_metrics->metric_sets, link) max_name_length = MAX2(max_name_length, strlen(metric_set->symbol_name)); comment("List of metric sets selectable with -m/--metrics=...\n"); list_for_each_entry(struct gputop_metric_set, metric_set, &context.ctx.gen_metrics->metric_sets, link) { comment("\t%s:%*s %s hw-config-guid=%s\n", metric_set->symbol_name, max_name_length - strlen(metric_set->symbol_name), "", metric_set->name, metric_set->hw_config_guid); } } static void print_metric_counter(struct gputop_client_context *ctx, const struct gputop_metric_set *metric_set) { int i, max_symbol_length = 0; comment("all: Timestamp"); for (i = 0; i < metric_set->n_counters; i++) { comment(",%s", metric_set->counters[i].symbol_name); max_symbol_length = MAX2(strlen(metric_set->counters[i].symbol_name), max_symbol_length); } comment("\n\n"); comment("Detailed:\n"); for (i = 0; i < metric_set->n_counters; i++) { char pretty_max_value[80]; gputop_client_context_pretty_print_max(ctx, &metric_set->counters[i], 1000000000ULL, pretty_max_value, sizeof(pretty_max_value)); comment("%s:%*s %s (max=%s)\n", metric_set->counters[i].symbol_name, max_symbol_length - strlen(metric_set->counters[i].symbol_name), "", metric_set->counters[i].desc, pretty_max_value); } } static void print_metric_column_names(void) { int i; for (i = 0; i < context.n_metric_columns; i++) { output("%*s%s%s", context.metric_columns[i].width - strlen(context.metric_columns[i].counter->symbol_name), "", context.metric_columns[i].counter->symbol_name, (i == (context.n_metric_columns - 1)) ? "" : ","); } output("\n"); for (i = 0; i < context.n_metric_columns; i++) { const char *units = unit_to_string(context.metric_columns[i].counter->units); output("%*s(%s)%s", context.metric_columns[i].width - strlen(units) - 2, "", units, (i == (context.n_metric_columns - 1)) ? "" : ","); } output("\n"); if (context.print_maximums) { for (i = 0; i < context.n_metric_columns; i++) { char pretty_max_value[80]; if (context.human_units) { gputop_client_context_pretty_print_max(&context.ctx, context.metric_columns[i].counter, context.ctx.oa_aggregation_period_ns, pretty_max_value, sizeof(pretty_max_value)); } else { snprintf(pretty_max_value, sizeof(pretty_max_value), "%f", gputop_client_context_max_value(&context.ctx, context.metric_columns[i].counter, 1000000000ULL)); } output("%*s%s%s", context.metric_columns[i].width - strlen(pretty_max_value), "", pretty_max_value, (i == (context.n_metric_columns - 1)) ? "" : ","); } output("\n\n"); } #if 0 /* Debugging column sizes */ for (i = 0; i < context.n_metric_columns; i++) { char num[10]; snprintf(num, sizeof(num), "(max=%u)", context.metric_columns[i].width); output("%*s%s%s", context.metric_columns[i].width - strlen(num), "", num, (i == (context.n_metric_columns - 1)) ? "" : ","); } output("\n"); #endif } static bool pid_is_child_of(uint32_t parent, uint32_t child) { static char path[80]; snprintf(path, sizeof(path), "/proc/%u/status", child); FILE *f = fopen(path, "r"); char *line = NULL; size_t n = 0; bool is_child = false; while (getline(&line, &n, f) > 0) { size_t len = strlen("PPid:"); if (!strncmp(line, "PPid:", len)) { uint32_t ppid = atoi(&line[len]); if (ppid == 0) is_child = false; else if (ppid == parent) is_child = true; else is_child = pid_is_child_of(parent, ppid); break; } } free(line); return is_child; } static bool match_process(struct gputop_hw_context *hw_context) { if (hw_context == NULL) { if (context.child_process_pid == 0) return true; return false; } if (!hw_context->process) return false; if (hw_context->process->pid == context.child_process_pid) return true; struct hash_entry *entry = _mesa_hash_table_search(context.process_ids, (void *) (uintptr_t) hw_context->process->pid); if (!entry) { bool is_child = pid_is_child_of(context.child_process_pid, hw_context->process->pid); _mesa_hash_table_insert(context.process_ids, (void *) (uintptr_t) hw_context->process->pid, (void *) (uintptr_t) is_child); return is_child; } return (bool) entry->data; } static void print_accumulated_columns(struct gputop_client_context *ctx, struct gputop_accumulated_samples *samples) { int i; for (i = 0; i < context.n_metric_columns; i++) { const struct gputop_metric_set_counter *counter = context.metric_columns[i].counter; char svalue[20]; if (counter == ×tamp_counter) { snprintf(svalue, sizeof(svalue), "%" PRIu64, samples->accumulator.first_timestamp); } else { double value = gputop_client_context_read_counter_value(ctx, samples, counter); if (context.human_units) gputop_client_pretty_print_value(counter->units, value, svalue, sizeof(svalue)); else snprintf(svalue, sizeof(svalue), "%.2f", value); } output("%*s%s%s", context.metric_columns[i].width - strlen(svalue), "", svalue, i == (context.n_metric_columns - 1) ? "" : ","); } output("\n"); } static void print_columns(struct gputop_client_context *ctx, struct gputop_hw_context *hw_context) { struct list_head *list; if (!match_process(hw_context)) return; context.n_accumulations++; list = hw_context == NULL ? &ctx->graphs : &hw_context->graphs; if (context.last_samples == NULL) { list_for_each_entry(struct gputop_accumulated_samples, samples, list, link) { print_accumulated_columns(ctx, samples); } context.last_samples = list_last_entry(list, struct gputop_accumulated_samples, link); } else { context.last_samples = list_last_entry(list, struct gputop_accumulated_samples, link); print_accumulated_columns(ctx, context.last_samples); } if (context.child_exited) quit(); } static bool handle_features() { static bool info_printed = false; struct gputop_client_context *ctx = &context.ctx; int i; if (!context.metric_name || (ctx->metric_set = gputop_client_context_symbol_to_metric_set(ctx, context.metric_name)) == NULL) { print_metrics(); return true; } if (!context.metric_columns) { if (!context.all_columns) { print_metric_counter(ctx, ctx->metric_set); return true; } else { context.n_metric_columns = ctx->metric_set->n_counters + 1; context.metric_columns = calloc(context.n_metric_columns, sizeof(context.metric_columns[0])); context.metric_columns[0].symbol_name = strdup("Timestamp"); for (i = 1; i < context.n_metric_columns; i++) { context.metric_columns[i].symbol_name = strdup(ctx->metric_set->counters[i - 1].symbol_name); } } } if (!context.metric_columns[0].counter) { for (i = 0; i < context.n_metric_columns; i++) { int j; if (!strcmp("Timestamp", context.metric_columns[i].symbol_name)) { context.metric_columns[i].counter = ×tamp_counter; } else { for (j = 0; j < ctx->metric_set->n_counters; j++) { if (!strcmp(ctx->metric_set->counters[j].symbol_name, context.metric_columns[i].symbol_name)) { context.metric_columns[i].counter = &ctx->metric_set->counters[j]; break; } } if (!context.metric_columns[i].counter) { comment("Unknown counter '%s'\n", context.metric_columns[i]); return true; } } context.metric_columns[i].width = MAX2(strlen(context.metric_columns[i].counter->symbol_name), strlen(unit_to_string(context.metric_columns[i].counter->units)) + unit_to_width(context.metric_columns[i].counter->units) + 1) + 1; } } if (!info_printed && ctx->features) { info_printed = true; print_system_info(); } if (context.print_headers) print_metric_column_names(); return false; } static void on_ready(gputop_connection_t *conn, void *user_data) { comment("Connected\n\n"); gputop_client_context_reset(&context.ctx, conn); } static void on_data(gputop_connection_t *conn, const void *data, size_t len, void *user_data) { static bool features_handled = false; gputop_client_context_handle_data(&context.ctx, data, len); if (!features_handled && context.ctx.features) { features_handled = true; if (handle_features()) { quit(); return; } if (context.child_process_pid != 0) gputop_client_context_add_tracepoint(&context.ctx, "i915/i915_context_create"); else gputop_client_context_start_sampling(&context.ctx); } else { if (!context.ctx.is_sampling) { bool all_tracepoints = true; list_for_each_entry(struct gputop_perf_tracepoint, tp, &context.ctx.perf_tracepoints, link) { if (tp->event_id == 0) all_tracepoints = false; } if (all_tracepoints) gputop_client_context_start_sampling(&context.ctx); } else { if (context.child_process_args && context.child_process_pid == -1) start_child_process(); } } } static void on_close(gputop_connection_t *conn, const char *error, void *user_data) { if (error) comment("Connection error : %s\n", error); context.ctx.connection = NULL; uv_stop(uv_default_loop()); } static const char *next_column(const char *string) { const char *s; if (!string) return NULL; s = strchr(string, ','); if (s) return s + 1; return NULL; } static void usage(void) { output("Usage: gputop-wrapper [options] [program args...]\n" "\n" "\t -h, --help Display this help\n" "\t -H, --host Host to connect to\n" "\t -p, --port Port on which the server is running\n" "\t -P, --period Accumulation period (in seconds, floating point)\n" "\t -m, --metric Metric set to use\n" "\t (prints out a list of metric sets with: -m list)\n" "\t -M, --max Outputs maximum counter values\n" "\t (first line after units)\n" "\t -c, --columns Columns to print out\n" "\t (prints out a lists of counters with: -c list,\n" "\t selects all counters with: -c all)\n" "\t -n, --no-human-units Disable human readable units (for machine readable output)\n" "\t -N, --no-headers Disable headers (for machine readable output)\n" "\t -O, --child-output Outputs the child's standard output to filename\n" "\t -o, --output Outputs gputop-wrapper's data to filename\n" "\t (disables human readable units)\n" "\t -w, --max-inactive-time