window system refactor

added imgui for gui rendering
added WindowInterface to Machine class enabling hardware to tap into window events for input and rendering
This commit is contained in:
Anthony Pesch 2016-03-15 23:51:05 -07:00
parent 3d491054c7
commit c836560bc9
61 changed files with 22404 additions and 9125 deletions

View File

@ -83,6 +83,11 @@ add_subdirectory(deps/glew-1.13.0/build/cmake EXCLUDE_FROM_ALL)
list(APPEND REDREAM_INCLUDE_DIRS deps/glew-1.13.0/include)
list(APPEND REDREAM_LIBS glew_s)
# imgui
add_library(imgui STATIC deps/imgui-1.47/imgui.cpp deps/imgui-1.47/imgui_draw.cpp)
list(APPEND REDREAM_INCLUDE_DIRS deps/imgui-1.47)
list(APPEND REDREAM_LIBS imgui)
# json11
add_library(json11 STATIC deps/json11/json11.cpp)
list(APPEND REDREAM_INCLUDE_DIRS deps/json11)
@ -92,9 +97,6 @@ target_compile_options(json11 PRIVATE -std=c++11)
# microprofile
list(APPEND REDREAM_INCLUDE_DIRS deps/microprofile)
# stb_truetype
list(APPEND REDREAM_INCLUDE_DIRS deps/stb_truetype-1.0.5)
# xbyak
list(APPEND REDREAM_INCLUDE_DIRS deps/xbyak-4.85)
@ -130,7 +132,6 @@ set(REDREAM_SOURCES
src/core/log.cc
src/core/string.cc
src/emu/emulator.cc
src/emu/profiler.cc
src/emu/tracer.cc
src/hw/aica/aica.cc
src/hw/gdrom/disc.cc
@ -169,10 +170,12 @@ set(REDREAM_SOURCES
src/renderer/gl_shader.cc
src/sys/exception_handler.cc
src/sys/filesystem.cc
src/sys/keycode.cc
src/sys/memory.cc
src/sys/network.cc
src/sys/window.cc
src/ui/imgui_impl.cc
src/ui/microprofile_impl.cc
src/ui/keycode.cc
src/ui/window.cc
src/main.cc)
if(WIN32)
@ -335,7 +338,6 @@ set(REDREAM_TEST_SOURCES
test/test_intrusive_list.cc
test/test_load_store_elimination_pass.cc
test/test_minmax_heap.cc
test/test_ring_buffer.cc
test/test_sh4.cc
${asm_inc})
list(REMOVE_ITEM REDREAM_TEST_SOURCES src/main.cc)

17
deps/imgui-1.47/.travis.yml vendored Normal file
View File

@ -0,0 +1,17 @@
language: cpp
os:
- linux
compiler:
- gcc
- clang
before_install:
- if [ $TRAVIS_OS_NAME == linux ]; then sudo add-apt-repository -y ppa:pyglfw/pyglfw && sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends libglfw3-dev libxrandr-dev libxi-dev libxxf86vm-dev; fi
- if [ $TRAVIS_OS_NAME == osx ]; then brew update && brew install glfw3; fi
script:
- make -C examples/opengl_example
- make -C examples/opengl3_example

21
deps/imgui-1.47/LICENSE vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2015 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.

168
deps/imgui-1.47/README.md vendored Normal file
View File

@ -0,0 +1,168 @@
dear imgui,
=====
[![Build Status](https://travis-ci.org/ocornut/imgui.svg?branch=master)](https://travis-ci.org/ocornut/imgui)
[![Coverity Status](https://scan.coverity.com/projects/4720/badge.svg)](https://scan.coverity.com/projects/4720)
(This library is free and will stay free, but needs your support to sustain its development. There are lots of desirable new features and maintenance to do. If you work for a company using ImGui or have the means to do so, please consider financial support)
[![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U)
dear imgui (AKA ImGui), is a bloat-free graphical user interface library for C++. It outputs vertex buffers that you can render in your 3D-pipeline enabled application. It is fast, portable, renderer agnostic and self-contained (no external dependencies).
ImGui is designed to enable fast iteration and empower programmers to create content creation tools and visualization/debug tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries.
ImGui is particularly suited to integration in realtime 3D applications, fullscreen applications, embedded applications, games, or any applications on consoles platforms where operating system features are non-standard.
ImGui is self-contained within a few files that you can easily copy and compile into your application/engine:
- imgui.cpp
- imgui.h
- imgui_demo.cpp
- imgui_draw.cpp
- imgui_internal.h
- imconfig.h (empty by default, user-editable)
- stb_rect_pack.h
- stb_textedit.h
- stb_truetype.h
No specific build process is required. You can add the .cpp files to your project or #include them from an existing file.
Your code passes mouse/keyboard inputs and settings to ImGui (see example applications for more details). After ImGui is setup, you can use it like in this example:
![screenshot of sample code alongside its output with ImGui](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01.png)
ImGui outputs vertex buffers and simple command-lists that you can render in your application. The number of draw calls and state changes is typically very small. Because it doesn't know or touch graphics state directly, you can call ImGui commands anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate ImGui with your existing codebase.
ImGui allows you create elaborate tools as well as very short-lived ones. On the extreme side of short-liveness: using the Edit&Continue feature of modern compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, etc.
Demo
----
You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me know! If you want to have a quick look at the features of ImGui, you can download Windows binaries of the demo app here.
- [imgui-demo-binaries-20150909.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20150909.zip) (Windows binaries, ImGui 1.46 WIP 2015/09/09, 4 executables, 505 KB)
Gallery
-------
![screenshot 1](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/examples_04.png)
![screenshot 2](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_01.png)
![screenshot 3](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_02.png)
![screenshot 4](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_03.png)
![screenshot 5](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v140/test_window_05_menus.png)
![screenshot 6](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/skinning_sample_02.png)
![screenshot 7](https://cloud.githubusercontent.com/assets/8225057/7903336/96f0fb7c-07d0-11e5-95d6-41c6a1595e5a.png)
ImGui can load TTF fonts. UTF-8 is supported for text display and input. Here using Arial Unicode font to display Japanese. Initialize custom font with:
```
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
// For Microsoft IME, pass your HWND to enable IME positioning:
io.ImeWindowHandle = my_hwnd;
```
![Japanese screenshot](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01_jp.png)
References
----------
The Immediate Mode GUI paradigm may at first appear unusual to some users. This is mainly because "Retained Mode" GUIs have been so widespread and predominant. The following links can give you a better understanding about how Immediate Mode GUIs works.
- [Johannes 'johno' Norneby's article](http://www.johno.se/book/imgui.html).
- [A presentation by Rickard Gustafsson and Johannes Algelind](http://www.cse.chalmers.se/edu/year/2011/course/TDA361/Advanced%20Computer%20Graphics/IMGUI.pdf).
- [Jari Komppa's tutorial on building an ImGui library](http://iki.fi/sol/imgui/).
- [Casey Muratori's original video that popularized the concept](https://mollyrocket.com/861).
See the [Links page](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to different languages and frameworks.
Frequently Asked Question (FAQ)
-------------------------------
<b>Where is the documentation?</b>
- The documentation is at the top of imgui.cpp + effectively imgui.h.
- Example code is in imgui_demo.cpp and particularly the ImGui::ShowTestWindow() function. It covers most features of ImGui so you can read the code and call the function itself to see its output.
- Standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder.
- We obviously needs better documentation! Consider contributing or becoming a [Patron](http://www.patreon.com/imgui) to promote this effort.
<b>Why the odd dual naming, "dear imgui" vs "ImGui"?</b>
The library started its life and is best known as "ImGui" only due to the fact that I didn't give it a proper name when I released it. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations. It seemed confusing and unfair to hog the name. To reduce the ambiguity without affecting existing codebases, I have decided on an alternate, longer name "dear imgui" that people can use to refer to this specific library in ambiguous situations.
<b>How do I update to a newer version of ImGui?</b>
<br><b>Can I have multiple widgets with the same label? Can I have widget without a label? (Yes)</b>
<br><b>I integrated ImGui in my engine and the text or lines are blurry..</b>
<br><b>I integrated ImGui in my engine and some elements are disappearing when I move windows around..</b>
<br><b>How can I load a different font than the default?</b>
<br><b>How can I load multiple fonts?</b>
<br><b>How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?</b>
See the FAQ in imgui.cpp for answers.
<b>How do you use ImGui on a platform that may not have a mouse or keyboard?</b>
I recommend using [Synergy](http://synergy-project.org) ([sources](https://github.com/synergy/synergy)). In particular, the _src/micro/uSynergy.c_ file contains a small client that you can use on any platform to connect to your host PC. You can seamlessly use your PC input devices from a video game console or a tablet. ImGui allows to increase the hit box of widgets (via the _TouchPadding_ setting) to accommodate a little for the lack of precision of touch inputs, but it is recommended you use a mouse to allow optimising for screen real-estate.
<b>Can you create elaborate/serious tools with ImGui?</b>
Yes. I have written data browsers, debuggers, profilers and all sort of non-trivial tools with the library. In my experience the simplicity of the API is very empowering. Your UI runs close to your live data. Make the tools always-on and everybody in the team will be inclined to create new tools (as opposed to more "offline" UI toolkits where only a fraction of your team effectively creates tools).
ImGui is very programmer centric and the immediate-mode GUI paradigm might requires you to readjust some habits before you can realize its full potential. Many programmers have unfortunately been taught by their environment to make unnecessarily complicated things. ImGui is about making things that are simple, efficient and powerful.
<b>Is ImGui fast?</b>
Probably fast enough for most uses. Down to the fundation of its visual design, ImGui is engineered to be fairly performant both in term of CPU and GPU usage. Running elaborate code and creating elaborate UI will of course have a cost but ImGui aims to minimize it.
Mileage may vary but the following screenshot can give you a rough idea of the cost of running and rendering UI code (In the case of a trivial demo application like this one, your driver/os setup are likely to be the bottleneck. Testing performance as part of a real application is recommended).
![performance screenshot](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v138/performance_01.png)
This is showing framerate for the full application loop on my 2011 iMac running Windows 7, OpenGL, AMD Radeon HD 6700M with an optimized executable. In contrast, librairies featuring higher-quality rendering and layouting techniques may have a higher resources footprint.
If you intend to display large lists of items (say, 1000+) it can be beneficial for your code to perform clipping manually - one way is using helpers such as ImGuiListClipper - in order to avoid submitting them to ImGui in the first place. Even though ImGui will discard your clipped items it still needs to calculate their size and that overhead will add up if you have thousands of items. If you can handle clipping and height positionning yourself then browsing a list with millions of items isn't a problem.
<b>Can you reskin the look of ImGui?</b>
You can alter the look of the interface to some degree: changing colors, sizes, padding, rounding, fonts. However, as ImGui is designed and optimised to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface.
<b>Why using C++ (as opposed to C)?</b>
ImGui takes advantage of a few C++ features for convenience but nothing anywhere Boost-insanity/quagmire. In particular, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience but could be removed.
There is an unofficial but reasonably maintained [c-api for ImGui](https://github.com/Extrawurst/cimgui) by Stephan Dilly. I would suggest using your target language functionality to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. It was really designed with C++ in mind and may not make the same amount of sense with another language. Also see [Links](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to other languages.
Donate
------
<b>Can I donate to support the development of ImGui?</b>
[![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U)
I'm currently an independent developer and your contributions are useful. I have setup an [**ImGui Patreon page**](http://www.patreon.com/imgui) if you want to donate and enable me to spend more time improving the library. If your company uses ImGui please consider making a contribution. One-off donations are also greatly appreciated. I am available for hire to work on or with ImGui. Thanks!
Credits
-------
Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indirect contributors to the GitHub. The early version of this library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com).
I first discovered imgui principles at [Q-Games](http://www.q-games.com) where Atman had dropped his own simple imgui implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating on it.
Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license).
Embeds [stb_textedit.h, stb_truetype.h, stb_rectpack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain).
Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. And everybody posting feedback, questions and patches on the GitHub.
ImGui development is financially supported on [**Patreon**](http://www.patreon.com/imgui).
Special supporters:
- Jetha Chan, Wild Sheep Studio, Pastagames, Mārtiņš Možeiko, Daniel Collin, Stefano Cristiano.
And:
- Michel Courtine, César Leblic, Dale Kim, Alex Evans, Rui Figueira, Paul Patrashcu, Jerome Lanquetot, Ctrl Alt Ninja, Paul Fleming, Neil Henning, Stephan Dilly, Neil Blakey-Milner, Aleksei, NeiloGD, Justin Paver, FiniteSol, Vincent Pancaldi, James Billot, Robin Hübner, furrtek, Eric, Simon Barratt, Game Atelier, Julian Bosch, Simon Lundmark, Vincent Hamm.
And other supporters; thanks!
License
-------
Dear ImGui is licensed under the MIT License, see LICENSE for more information.

51
deps/imgui-1.47/imconfig.h vendored Normal file
View File

@ -0,0 +1,51 @@
//-----------------------------------------------------------------------------
// USER IMPLEMENTATION
// This file contains compile-time options for ImGui.
// Other options (memory allocation overrides, callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO().
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Include imgui_user.h at the end of imgui.h
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Don't implement default handlers for Windows (so as not to link with OpenClipboard() and others Win32 functions)
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS
//---- Don't implement help and test window functionality (ShowUserGuide()/ShowStyleEditor()/ShowTestWindow() methods will be empty)
//#define IMGUI_DISABLE_TEST_WINDOWS
//---- Don't define obsolete functions names
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//---- Implement STB libraries in a namespace to avoid conflicts
//#define IMGUI_STB_NAMESPACE ImGuiStb
//---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4.
/*
#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); }
*/
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
//---- e.g. create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers.
/*
namespace ImGui
{
void Value(const char* prefix, const MyMatrix44& v, const char* float_format = NULL);
}
*/

9321
deps/imgui-1.47/imgui.cpp vendored Normal file

File diff suppressed because it is too large Load Diff

1308
deps/imgui-1.47/imgui.h vendored Normal file

File diff suppressed because it is too large Load Diff

2362
deps/imgui-1.47/imgui_demo.cpp vendored Normal file

File diff suppressed because it is too large Load Diff

2263
deps/imgui-1.47/imgui_draw.cpp vendored Normal file

File diff suppressed because it is too large Load Diff

731
deps/imgui-1.47/imgui_internal.h vendored Normal file
View File

@ -0,0 +1,731 @@
// dear imgui, v1.47
// (internals)
// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility!
// Implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators)
// #define IMGUI_DEFINE_MATH_OPERATORS
#pragma once
#ifndef IMGUI_VERSION
#error Must include imgui.h before imgui_internal.h
#endif
#include <stdio.h> // FILE*
#include <math.h> // sqrtf()
#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
//-----------------------------------------------------------------------------
// Forward Declarations
//-----------------------------------------------------------------------------
struct ImRect;
struct ImGuiColMod;
struct ImGuiStyleMod;
struct ImGuiGroupData;
struct ImGuiSimpleColumns;
struct ImGuiDrawContext;
struct ImGuiTextEditState;
struct ImGuiIniData;
struct ImGuiMouseCursorData;
struct ImGuiPopupRef;
struct ImGuiState;
struct ImGuiWindow;
typedef int ImGuiLayoutType; // enum ImGuiLayoutType_
typedef int ImGuiButtonFlags; // enum ImGuiButtonFlags_
typedef int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_
typedef int ImGuiSliderFlags; // enum ImGuiSliderFlags_
//-------------------------------------------------------------------------
// STB libraries
//-------------------------------------------------------------------------
namespace ImGuiStb
{
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#endif
#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"
#ifdef __clang__
#pragma clang diagnostic pop
#endif
} // namespace ImGuiStb
//-----------------------------------------------------------------------------
// Context
//-----------------------------------------------------------------------------
extern IMGUI_API ImGuiState* GImGui;
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
#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* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0);
IMGUI_API bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c);
static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; }
static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; }
// Helpers: String
IMGUI_API int ImStricmp(const char* str1, const char* str2);
IMGUI_API int ImStrnicmp(const char* str1, const char* str2, int count);
IMGUI_API char* ImStrdup(const char* str);
IMGUI_API int ImStrlenW(const ImWchar* str);
IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line
IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end);
IMGUI_API int ImFormatString(char* buf, int buf_size, const char* fmt, ...) IM_PRINTFARGS(3);
IMGUI_API int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args);
// Helpers: Math
// We are keeping those not leaking to the user by default, in the case the user has implicit cast operators between ImVec2 and its own types (when IM_VEC2_CLASS_EXTRA is defined)
#ifdef IMGUI_DEFINE_MATH_OPERATORS
static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); }
static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); }
static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); }
static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); }
static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); }
static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); }
static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; }
static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; }
static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; }
static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; }
static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); }
#endif
static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; }
static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; }
static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; }
static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; }
static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); }
static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); }
static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); }
static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; }
static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; }
static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); }
static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; }
static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; }
static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / sqrtf(d); return fail_value; }
static inline ImVec2 ImRound(ImVec2 v) { return ImVec2((float)(int)v.x, (float)(int)v.y); }
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
enum ImGuiButtonFlags_
{
ImGuiButtonFlags_Repeat = 1 << 0,
ImGuiButtonFlags_PressedOnClick = 1 << 1, // return pressed on click only (default requires click+release)
ImGuiButtonFlags_PressedOnRelease = 1 << 2, // return pressed on release only (default requires click+release)
ImGuiButtonFlags_FlattenChilds = 1 << 3,
ImGuiButtonFlags_DontClosePopups = 1 << 4,
ImGuiButtonFlags_Disabled = 1 << 5,
ImGuiButtonFlags_AlignTextBaseLine = 1 << 6,
ImGuiButtonFlags_NoKeyModifiers = 1 << 7
};
enum ImGuiTreeNodeFlags_
{
ImGuiTreeNodeFlags_DefaultOpen = 1 << 0,
ImGuiTreeNodeFlags_NoAutoExpandOnLog = 1 << 1
};
enum ImGuiSliderFlags_
{
ImGuiSliderFlags_Vertical = 1 << 0,
};
enum ImGuiSelectableFlagsPrivate_
{
// NB: need to be in sync with last value of ImGuiSelectableFlags_
ImGuiSelectableFlags_Menu = 1 << 2,
ImGuiSelectableFlags_MenuItem = 1 << 3,
ImGuiSelectableFlags_Disabled = 1 << 4,
ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 5
};
// FIXME: this is in development, not exposed/functional as a generic feature yet.
enum ImGuiLayoutType_
{
ImGuiLayoutType_Vertical,
ImGuiLayoutType_Horizontal
};
enum ImGuiPlotType
{
ImGuiPlotType_Lines,
ImGuiPlotType_Histogram
};
enum ImGuiDataType
{
ImGuiDataType_Int,
ImGuiDataType_Float
};
// 2D axis aligned bounding-box
// NB: we can't rely on ImVec2 math operators being available here
struct IMGUI_API ImRect
{
ImVec2 Min; // Upper-left
ImVec2 Max; // Lower-right
ImRect() : Min(FLT_MAX,FLT_MAX), Max(-FLT_MAX,-FLT_MAX) {}
ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {}
ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {}
ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {}
ImVec2 GetCenter() const { return ImVec2((Min.x+Max.x)*0.5f, (Min.y+Max.y)*0.5f); }
ImVec2 GetSize() const { return ImVec2(Max.x-Min.x, Max.y-Min.y); }
float GetWidth() const { return Max.x-Min.x; }
float GetHeight() const { return Max.y-Min.y; }
ImVec2 GetTL() const { return Min; } // Top-left
ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right
ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left
ImVec2 GetBR() const { return Max; } // Bottom-right
bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; }
bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; }
bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; }
void Add(const ImVec2& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; }
void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.Max.y; }
void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; }
void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; }
void Reduce(const ImVec2& amount) { Min.x += amount.x; Min.y += amount.y; Max.x -= amount.x; Max.y -= amount.y; }
void Clip(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; }
void Round() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; }
ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const
{
if (!on_edge && Contains(p))
return p;
if (p.x > Max.x) p.x = Max.x;
else if (p.x < Min.x) p.x = Min.x;
if (p.y > Max.y) p.y = Max.y;
else if (p.y < Min.y) p.y = Min.y;
return p;
}
};
// Stacked color modifier, backup of modified data so we can restore it
struct ImGuiColMod
{
ImGuiCol Col;
ImVec4 PreviousValue;
};
// Stacked style modifier, backup of modified data so we can restore it
struct ImGuiStyleMod
{
ImGuiStyleVar Var;
ImVec2 PreviousValue;
};
// Stacked data for BeginGroup()/EndGroup()
struct ImGuiGroupData
{
ImVec2 BackupCursorPos;
ImVec2 BackupCursorMaxPos;
float BackupIndentX;
float BackupCurrentLineHeight;
float BackupCurrentLineTextBaseOffset;
float BackupLogLinePosY;
bool AdvanceCursor;
};
// Per column data for Columns()
struct ImGuiColumnData
{
float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right)
//float IndentX;
};
// Simple column measurement currently used for MenuItem() only. This is very short-sighted for now and NOT a generic helper.
struct IMGUI_API ImGuiSimpleColumns
{
int Count;
float Spacing;
float Width, NextWidth;
float Pos[8], NextWidths[8];
ImGuiSimpleColumns();
void Update(int count, float spacing, bool clear);
float DeclColumns(float w0, float w1, float w2);
float CalcExtraSpace(float avail_w);
};
// Internal state of the currently focused/edited text input box
struct IMGUI_API ImGuiTextEditState
{
ImGuiID Id; // widget id owning the text state
ImVector<ImWchar> Text; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer.
ImVector<char> InitialText; // backup of end-user buffer at the time of focus (in UTF-8, unaltered)
ImVector<char> TempTextBuffer;
int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format.
int BufSizeA; // end-user buffer size
float ScrollX;
ImGuiStb::STB_TexteditState StbState;
float CursorAnim;
bool CursorFollow;
bool SelectedAllMouseLock;
ImGuiTextEditState() { memset(this, 0, sizeof(*this)); }
void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); }
bool HasSelection() const { return StbState.select_start != StbState.select_end; }
void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; }
void SelectAll() { StbState.select_start = 0; StbState.select_end = CurLenW; StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; }
void OnKeyPressed(int key);
};
// Data saved in imgui.ini file
struct ImGuiIniData
{
char* Name;
ImGuiID ID;
ImVec2 Pos;
ImVec2 Size;
bool Collapsed;
};
// Mouse cursor data (used when io.MouseDrawCursor is set)
struct ImGuiMouseCursorData
{
ImGuiMouseCursor Type;
ImVec2 HotOffset;
ImVec2 Size;
ImVec2 TexUvMin[2];
ImVec2 TexUvMax[2];
};
// Storage for current popup stack
struct ImGuiPopupRef
{
ImGuiID PopupID; // Set on OpenPopup()
ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup()
ImGuiWindow* ParentWindow; // Set on OpenPopup()
ImGuiID ParentMenuSet; // Set on OpenPopup()
ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup
ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupID = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; }
};
// Main state for ImGui
struct ImGuiState
{
bool Initialized;
ImGuiIO IO;
ImGuiStyle Style;
ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back()
float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize()
float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters.
ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvForWhite
float Time;
int FrameCount;
int FrameCountEnded;
int FrameCountRendered;
ImVector<ImGuiWindow*> Windows;
ImVector<ImGuiWindow*> WindowsSortBuffer;
ImGuiWindow* CurrentWindow; // Being drawn into
ImVector<ImGuiWindow*> CurrentWindowStack;
ImGuiWindow* FocusedWindow; // Will catch keyboard inputs
ImGuiWindow* HoveredWindow; // Will catch mouse inputs
ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only)
ImGuiID HoveredId; // Hovered widget
bool HoveredIdAllowOverlap;
ImGuiID HoveredIdPreviousFrame;
ImGuiID ActiveId; // Active widget
ImGuiID ActiveIdPreviousFrame;
bool ActiveIdIsAlive;
bool ActiveIdIsJustActivated; // Set at the time of activation for one frame
bool ActiveIdAllowOverlap; // Set only by active widget
ImGuiWindow* ActiveIdWindow;
ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window. Pointer is only valid if ActiveID is the "#MOVE" identifier of a window.
ImVector<ImGuiIniData> Settings; // .ini Settings
float SettingsDirtyTimer; // Save .ini settinngs on disk when time reaches zero
int DisableHideTextAfterDoubleHash;
ImVector<ImGuiColMod> ColorModifiers; // Stack for PushStyleColor()/PopStyleColor()
ImVector<ImGuiStyleMod> StyleModifiers; // Stack for PushStyleVar()/PopStyleVar()
ImVector<ImFont*> FontStack; // Stack for PushFont()/PopFont()
ImVector<ImGuiPopupRef> OpenedPopupStack; // Which popups are open (persistent)
ImVector<ImGuiPopupRef> CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame)
// Storage for SetNexWindow** and SetNextTreeNode*** functions
ImVec2 SetNextWindowPosVal;
ImVec2 SetNextWindowSizeVal;
ImVec2 SetNextWindowContentSizeVal;
bool SetNextWindowCollapsedVal;
ImGuiSetCond SetNextWindowPosCond;
ImGuiSetCond SetNextWindowSizeCond;
ImGuiSetCond SetNextWindowContentSizeCond;
ImGuiSetCond SetNextWindowCollapsedCond;
bool SetNextWindowFocus;
bool SetNextTreeNodeOpenedVal;
ImGuiSetCond SetNextTreeNodeOpenedCond;
// Render
ImDrawData RenderDrawData; // Main ImDrawData instance to pass render information to the user
ImVector<ImDrawList*> RenderDrawLists[3];
float ModalWindowDarkeningRatio;
ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays
ImGuiMouseCursor MouseCursor;
ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_];
// Widget state
ImGuiTextEditState InputTextState;
ImFont InputTextPasswordFont;
ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc.
ImGuiStorage ColorEditModeStorage; // Store user selection of color edit mode
ImVec2 ActiveClickDeltaToCenter;
float DragCurrentValue; // Currently dragged value, always float, not rounded by end-user precision settings
ImVec2 DragLastMouseDelta;
float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio
float DragSpeedScaleSlow;
float DragSpeedScaleFast;
ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage?
char Tooltip[1024];
char* PrivateClipboard; // If no custom clipboard handler is defined
ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor
// Logging
bool LogEnabled;
FILE* LogFile; // If != NULL log to stdout/ file
ImGuiTextBuffer* LogClipboard; // Else log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators.
int LogStartDepth;
int LogAutoExpandMaxDepth;
// Misc
float FramerateSecPerFrame[120]; // calculate estimate of framerate for user
int FramerateSecPerFrameIdx;
float FramerateSecPerFrameAccum;
bool CaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags
bool CaptureKeyboardNextFrame;
char TempBuffer[1024*3+1]; // temporary text buffer
ImGuiState()
{
Initialized = false;
Font = NULL;
FontSize = FontBaseSize = 0.0f;
FontTexUvWhitePixel = ImVec2(0.0f, 0.0f);
Time = 0.0f;
FrameCount = 0;
FrameCountEnded = FrameCountRendered = -1;
CurrentWindow = NULL;
FocusedWindow = NULL;
HoveredWindow = NULL;
HoveredRootWindow = NULL;
HoveredId = 0;
HoveredIdAllowOverlap = false;
HoveredIdPreviousFrame = 0;
ActiveId = 0;
ActiveIdPreviousFrame = 0;
ActiveIdIsAlive = false;
ActiveIdIsJustActivated = false;
ActiveIdAllowOverlap = false;
ActiveIdWindow = NULL;
MovedWindow = NULL;
SettingsDirtyTimer = 0.0f;
DisableHideTextAfterDoubleHash = 0;
SetNextWindowPosVal = ImVec2(0.0f, 0.0f);
SetNextWindowSizeVal = ImVec2(0.0f, 0.0f);
SetNextWindowCollapsedVal = false;
SetNextWindowPosCond = 0;
SetNextWindowSizeCond = 0;
SetNextWindowCollapsedCond = 0;
SetNextWindowFocus = false;
SetNextTreeNodeOpenedVal = false;
SetNextTreeNodeOpenedCond = 0;
ScalarAsInputTextId = 0;
ActiveClickDeltaToCenter = ImVec2(0.0f, 0.0f);
DragCurrentValue = 0.0f;
DragLastMouseDelta = ImVec2(0.0f, 0.0f);
DragSpeedDefaultRatio = 0.01f;
DragSpeedScaleSlow = 0.01f;
DragSpeedScaleFast = 10.0f;
ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f);
memset(Tooltip, 0, sizeof(Tooltip));
PrivateClipboard = NULL;
OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f);
ModalWindowDarkeningRatio = 0.0f;
OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging
MouseCursor = ImGuiMouseCursor_Arrow;
LogEnabled = false;
LogFile = NULL;
LogClipboard = NULL;
LogStartDepth = 0;
LogAutoExpandMaxDepth = 2;
memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
FramerateSecPerFrameIdx = 0;
FramerateSecPerFrameAccum = 0.0f;
CaptureMouseNextFrame = CaptureKeyboardNextFrame = false;
}
};
// Transient per-window data, reset at the beginning of the frame
// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiDrawContext is quite tenuous and could be reconsidered.
struct IMGUI_API ImGuiDrawContext
{
ImVec2 CursorPos;
ImVec2 CursorPosPrevLine;
ImVec2 CursorStartPos;
ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame
float CurrentLineHeight;
float CurrentLineTextBaseOffset;
float PrevLineHeight;
float PrevLineTextBaseOffset;
float LogLinePosY;
int TreeDepth;
ImGuiID LastItemID;
ImRect LastItemRect;
bool LastItemHoveredAndUsable; // Item rectangle is hovered, and its window is currently interactable with (not blocked by a popup preventing access to the window)
bool LastItemHoveredRect; // Item rectangle is hovered, but its window may or not be currently interactable with (might be blocked by a popup preventing access to the window)
bool MenuBarAppending;
float MenuBarOffsetX;
ImVector<ImGuiWindow*> ChildWindows;
ImGuiStorage* StateStorage;
ImGuiLayoutType LayoutType;
// We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings.
float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window
float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f]
bool AllowKeyboardFocus; // == AllowKeyboardFocusStack.back() [empty == true]
bool ButtonRepeat; // == ButtonRepeatStack.back() [empty == false]
ImVector<float> ItemWidthStack;
ImVector<float> TextWrapPosStack;
ImVector<bool> AllowKeyboardFocusStack;
ImVector<bool> ButtonRepeatStack;
ImVector<ImGuiGroupData>GroupStack;
ImGuiColorEditMode ColorEditMode;
int StackSizesBackup[6]; // Store size of various stacks for asserting
float IndentX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.)
float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API.
int ColumnsCurrent;
int ColumnsCount;
float ColumnsMinX;
float ColumnsMaxX;
float ColumnsStartPosY;
float ColumnsCellMinY;
float ColumnsCellMaxY;
bool ColumnsShowBorders;
ImGuiID ColumnsSetID;
ImVector<ImGuiColumnData> ColumnsData;
ImGuiDrawContext()
{
CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f);
CurrentLineHeight = PrevLineHeight = 0.0f;
CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f;
LogLinePosY = -1.0f;
TreeDepth = 0;
LastItemID = 0;
LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f);
LastItemHoveredAndUsable = LastItemHoveredRect = false;
MenuBarAppending = false;
MenuBarOffsetX = 0.0f;
StateStorage = NULL;
LayoutType = ImGuiLayoutType_Vertical;
ItemWidth = 0.0f;
ButtonRepeat = false;
AllowKeyboardFocus = true;
TextWrapPos = -1.0f;
ColorEditMode = ImGuiColorEditMode_RGB;
memset(StackSizesBackup, 0, sizeof(StackSizesBackup));
IndentX = 0.0f;
ColumnsOffsetX = 0.0f;
ColumnsCurrent = 0;
ColumnsCount = 1;
ColumnsMinX = ColumnsMaxX = 0.0f;
ColumnsStartPosY = 0.0f;
ColumnsCellMinY = ColumnsCellMaxY = 0.0f;
ColumnsShowBorders = true;
ColumnsSetID = 0;
}
};
// Windows data
struct IMGUI_API ImGuiWindow
{
char* Name;
ImGuiID ID;
ImGuiWindowFlags Flags;
ImVec2 PosFloat;
ImVec2 Pos; // Position rounded-up to nearest pixel
ImVec2 Size; // Current size (==SizeFull or collapsed title bar size)
ImVec2 SizeFull; // Size when non collapsed
ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame
ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize()
ImVec2 WindowPadding; // Window padding at the time of begin. We need to lock it, in particular manipulation of the ShowBorder would have an effect
ImGuiID MoveID; // == window->GetID("#MOVE")
ImVec2 Scroll;
ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change)
ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered
bool ScrollbarX, ScrollbarY;
ImVec2 ScrollbarSizes; //
bool Active; // Set to true on Begin()
bool WasActive;
bool Accessed; // Set to true when any widget access the current window
bool Collapsed; // Set when collapsing window to become only title-bar
bool SkipItems; // == Visible && !Collapsed
int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs)
ImGuiID PopupID; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling)
int AutoFitFramesX, AutoFitFramesY;
bool AutoFitOnlyGrows;
int AutoPosLastDirection;
int HiddenFrames;
int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag.
int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag.
int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag.
bool SetWindowPosCenterWanted;
ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame
ImVector<ImGuiID> IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack
ImRect ClipRect; // = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2.
ImRect ClippedWindowRect; // = ClipRect just after setup in Begin()
int LastFrameActive;
float ItemWidthDefault;
ImGuiSimpleColumns MenuColumns; // Simplified columns storage for menu items
ImGuiStorage StateStorage;
float FontWindowScale; // Scale multiplier per-window
ImDrawList* DrawList;
ImGuiWindow* RootWindow;
ImGuiWindow* RootNonPopupWindow;
// Focus
int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister()
int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through)
int FocusIdxAllRequestCurrent; // Item being requested for focus
int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus
int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame)
int FocusIdxTabRequestNext; // "
public:
ImGuiWindow(const char* name);
~ImGuiWindow();
ImGuiID GetID(const char* str, const char* str_end = NULL);
ImGuiID GetID(const void* ptr);
ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); }
float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; }
float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; }
ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); }
float MenuBarHeight() const { return (Flags & ImGuiWindowFlags_MenuBar) ? CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f : 0.0f; }
ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); }
};
//-----------------------------------------------------------------------------
// Internal API
// No guarantee of forward compatibility here.
//-----------------------------------------------------------------------------
namespace ImGui
{
// We should always have a CurrentWindow in the stack (there is an implicit "Debug" window)
// If this ever crash because g.CurrentWindow is NULL it means that either
// - ImGui::NewFrame() has never been called, which is illegal.
// - You are calling ImGui functions after ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal.
inline ImGuiWindow* GetCurrentWindowRead() { ImGuiState& g = *GImGui; return g.CurrentWindow; }
inline ImGuiWindow* GetCurrentWindow() { ImGuiState& g = *GImGui; g.CurrentWindow->Accessed = true; return g.CurrentWindow; }
IMGUI_API ImGuiWindow* GetParentWindow();
IMGUI_API void FocusWindow(ImGuiWindow* window);
IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window);
IMGUI_API void SetHoveredID(ImGuiID id);
IMGUI_API void KeepAliveID(ImGuiID id);
IMGUI_API void EndFrame(); // Automatically called by Render()
IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f);
IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f);
IMGUI_API bool ItemAdd(const ImRect& bb, const ImGuiID* id);
IMGUI_API bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged);
IMGUI_API bool IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs = false);
IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop = true); // Return true if focus is requested
IMGUI_API void FocusableItemUnregister(ImGuiWindow* window);
IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y);
IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x);
IMGUI_API void SetItemAllowOverlap(); // Allow last item to be overlapped by a subsequent item
IMGUI_API void OpenPopupEx(const char* str_id, bool reopen_existing);
inline IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul) { ImVec4 c = GImGui->Style.Colors[idx]; c.w *= GImGui->Style.Alpha * alpha_mul; return ImGui::ColorConvertFloat4ToU32(c); }
inline IMGUI_API ImU32 GetColorU32(const ImVec4& col) { ImVec4 c = col; c.w *= GImGui->Style.Alpha; return ImGui::ColorConvertFloat4ToU32(c); }
// NB: All position are in absolute pixels coordinates (not window coordinates)
// FIXME: Refactor all RenderText* functions into one.
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, ImGuiAlign align = ImGuiAlign_Default, const ImVec2* clip_min = NULL, const ImVec2* clip_max = NULL);
IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f);
IMGUI_API void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale = 1.0f, bool shadow = false);
IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col);
IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_existing_clip_rect = true);
IMGUI_API void PopClipRect();
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 SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags = 0);
IMGUI_API bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power);
IMGUI_API bool SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format);
IMGUI_API bool DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power);
IMGUI_API bool DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power);
IMGUI_API bool DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format);
IMGUI_API bool InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags);
IMGUI_API bool InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags);
IMGUI_API bool InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags);
IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision);
IMGUI_API bool TreeNodeBehaviorIsOpened(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging
IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size);
IMGUI_API int ParseFormatPrecision(const char* fmt, int default_value);
IMGUI_API float RoundScalar(float value, int decimal_precision);
} // namespace ImGuiP
#ifdef _MSC_VER
#pragma warning (pop)
#endif

573
deps/imgui-1.47/stb_rect_pack.h vendored Normal file
View File

@ -0,0 +1,573 @@
// stb_rect_pack.h - v0.08 - 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
// Bugfixes / warning fixes
// Jeremy Jaussaud
//
// Version history:
//
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//
// LICENSE
//
// This software is in the public domain. Where that dedication is not
// recognized, you are granted a perpetual, irrevocable license to copy,
// distribute, and modify this file as you see fit.
//////////////////////////////////////////////////////////////////////////////
//
// 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 void 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.
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 <stdlib.h>
#define STBRP_SORT qsort
#endif
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#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)
{
(void)c;
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
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);
{
stbrp_node *L1 = NULL, *L2 = NULL;
int count=0;
cur = context->active_head;
while (cur) {
L1 = cur;
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
L2 = cur;
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
static int rect_height_compare(const void *a, const void *b)
{
stbrp_rect *p = (stbrp_rect *) a;
stbrp_rect *q = (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 rect_width_compare(const void *a, const void *b)
{
stbrp_rect *p = (stbrp_rect *) a;
stbrp_rect *q = (stbrp_rect *) b;
if (p->w > q->w)
return -1;
if (p->w < q->w)
return 1;
return (p->h > q->h) ? -1 : (p->h < q->h);
}
static int rect_original_order(const void *a, const void *b)
{
stbrp_rect *p = (stbrp_rect *) a;
stbrp_rect *q = (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 void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i;
// 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
for (i=0; i < num_rects; ++i)
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
}
#endif

1264
deps/imgui-1.47/stb_textedit.h vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,133 +0,0 @@
#ifndef RING_BUFFER_H
#define RING_BUFFER_H
#include <iterator>
#include "core/assert.h"
namespace re {
template <typename T>
class RingBuffer {
template <bool is_const_iterator>
class shared_iterator
: public std::iterator<std::random_access_iterator_tag, T> {
friend class RingBuffer;
public:
typedef RingBuffer<T> *parent_type;
typedef shared_iterator<is_const_iterator> self_type;
typedef int difference_type;
typedef typename std::conditional<is_const_iterator, T const, T>::type
reference;
typedef typename std::conditional<is_const_iterator, T const *, T *>::type
pointer;
self_type &operator++() {
index_++;
return *this;
}
self_type operator++(int) {
self_type old(*this);
++(*this);
return old;
}
self_type &operator--() {
index_--;
return *this;
}
self_type operator--(int) {
self_type old(*this);
--(*this);
return old;
}
// support std::distance
difference_type operator-(const self_type &other) {
return static_cast<difference_type>(index_ - other.index_);
}
// support std::advance
void operator+=(difference_type diff) { index_ += diff; }
reference operator*() { return (*parent_)[index_]; }
pointer operator->() { return &(*parent_)[index_]; }
bool operator==(const self_type &other) const {
return parent_ == other.parent_ && index_ == other.index_;
}
bool operator!=(const self_type &other) const { return !(other == *this); }
private:
shared_iterator(parent_type parent, size_t index)
: parent_(parent), index_(index) {}
parent_type parent_;
size_t index_;
};
public:
typedef shared_iterator<false> iterator;
typedef shared_iterator<true> const_iterator;
const_iterator begin() const { return const_iterator(this, 0); }
const_iterator end() const { return const_iterator(this, Size()); }
iterator begin() { return iterator(this, 0); }
iterator end() { return iterator(this, Size()); }
RingBuffer(size_t max) : max_(max), front_(0), back_(0) {
buffer_ = new T[max_];
}
~RingBuffer() { delete[] buffer_; }
const T &operator[](size_t index) const {
return buffer_[(front_ + index) % max_];
}
T &operator[](size_t index) { return buffer_[(front_ + index) % max_]; }
const T &front() const { return buffer_[front_ % max_]; }
T &front() { return buffer_[front_ % max_]; }
const T &back() const { return buffer_[(back_ - 1) % max_]; }
T &back() { return buffer_[(back_ - 1) % max_]; }
size_t Size() const { return back_ - front_; }
bool Empty() const { return !Size(); }
bool Full() const { return Size() >= max_; }
void Clear() { back_ = front_ = 0; }
void PushBack(const T &el) {
// if the buffer is wrapping, advance front_
if (back_ - front_ >= max_) {
front_++;
}
buffer_[back_++ % max_] = el;
}
void PopBack() {
DCHECK(back_ > front_);
back_--;
}
void PopFront() {
DCHECK(front_ < back_);
front_++;
}
private:
T *buffer_;
const size_t max_;
size_t front_;
size_t back_;
};
}
#endif

View File

@ -1,18 +1,16 @@
#include <thread>
#include <algorithm>
#include <gflags/gflags.h>
#include "emu/emulator.h"
#include "emu/profiler.h"
#include "hw/aica/aica.h"
#include "hw/gdrom/gdrom.h"
#include "hw/holly/holly.h"
#include "hw/holly/pvr2.h"
#include "hw/holly/tile_renderer.h"
#include "hw/holly/trace.h"
#include "hw/holly/tile_accelerator.h"
#include "hw/maple/maple.h"
#include "hw/sh4/sh4.h"
#include "hw/dreamcast.h"
#include "hw/memory.h"
#include "renderer/gl_backend.h"
#include "ui/window.h"
using namespace re;
using namespace re::emu;
@ -23,41 +21,26 @@ using namespace re::hw::holly;
using namespace re::hw::maple;
using namespace re::hw::sh4;
using namespace re::renderer;
using namespace re::sys;
using namespace re::ui;
DEFINE_string(bios, "dc_boot.bin", "Path to BIOS");
DEFINE_string(flash, "dc_flash.bin", "Path to flash ROM");
Emulator::Emulator() : rb_(nullptr), tile_renderer_(nullptr), speed_() {}
Emulator::Emulator(ui::Window &window) : window_(window) {
window_.AddListener(this);
}
Emulator::~Emulator() {
delete rb_;
delete tile_renderer_;
window_.RemoveListener(this);
DestroyDreamcast();
}
void Emulator::Run(const char *path) {
if (!window_.Init()) {
return;
}
// initialize renderer backend
rb_ = new GLBackend(window_);
if (!rb_->Init()) {
return;
}
// initialize dreamcast machine and all dependent hardware
if (!CreateDreamcast()) {
return;
}
// setup tile renderer with the renderer backend and the dreamcast's
// internal textue cache
tile_renderer_ = new TileRenderer(*rb_, *dc_.ta);
if (!LoadBios(FLAGS_bios.c_str())) {
return;
}
@ -79,17 +62,12 @@ void Emulator::Run(const char *path) {
// start running
static const std::chrono::nanoseconds MACHINE_STEP = HZ_TO_NANO(1000);
static const std::chrono::nanoseconds FRAME_STEP = HZ_TO_NANO(60);
static const std::chrono::nanoseconds SAMPLE_PERIOD = HZ_TO_NANO(10);
auto current_time = std::chrono::high_resolution_clock::now();
auto last_time = current_time;
auto next_machine_time = current_time;
auto next_frame_time = current_time;
auto next_sample_time = current_time;
auto host_time = std::chrono::nanoseconds(0);
auto guest_time = std::chrono::nanoseconds(0);
running_ = true;
@ -97,33 +75,19 @@ void Emulator::Run(const char *path) {
current_time = std::chrono::high_resolution_clock::now();
last_time = current_time;
// run machine
// run dreamcast machine
if (current_time > next_machine_time) {
dc_.Tick(MACHINE_STEP);
host_time += std::chrono::high_resolution_clock::now() - last_time;
guest_time += MACHINE_STEP;
next_machine_time = current_time + MACHINE_STEP;
}
// pump input / render frame
// run local frame
if (current_time > next_frame_time) {
PumpEvents();
RenderFrame();
window_.PumpEvents();
next_frame_time = current_time + FRAME_STEP;
}
// update debug stats
if (current_time > next_sample_time) {
float speed =
(guest_time.count() / static_cast<float>(host_time.count())) * 100.0f;
speed_ = *reinterpret_cast<uint32_t *>(&speed);
host_time = std::chrono::nanoseconds(0);
guest_time = std::chrono::nanoseconds(0);
next_sample_time = current_time + SAMPLE_PERIOD;
}
}
}
@ -134,7 +98,7 @@ bool Emulator::CreateDreamcast() {
dc_.holly = new Holly(&dc_);
dc_.maple = new Maple(&dc_);
dc_.pvr = new PVR2(&dc_);
dc_.ta = new TileAccelerator(&dc_, rb_);
dc_.ta = new TileAccelerator(&dc_, window_.render_backend());
if (!dc_.Init()) {
DestroyDreamcast();
@ -159,8 +123,6 @@ void Emulator::DestroyDreamcast() {
dc_.pvr = nullptr;
delete dc_.ta;
dc_.ta = nullptr;
delete dc_.trace_writer;
dc_.trace_writer = nullptr;
}
bool Emulator::LoadBios(const char *path) {
@ -260,86 +222,17 @@ bool Emulator::LaunchGDI(const char *path) {
return true;
}
void Emulator::ToggleTracing() {
if (!dc_.trace_writer) {
char filename[PATH_MAX];
GetNextTraceFilename(filename, sizeof(filename));
void Emulator::OnPaint(bool show_main_menu) { dc_.OnPaint(show_main_menu); }
dc_.trace_writer = new TraceWriter();
if (!dc_.trace_writer->Open(filename)) {
delete dc_.trace_writer;
dc_.trace_writer = nullptr;
LOG_INFO("Failed to start tracing");
return;
void Emulator::OnKeyDown(Keycode code, int16_t value) {
if (code == K_F1) {
if (value) {
window_.EnableMainMenu(!window_.MainMenuEnabled());
}
// clear texture cache in order to generate insert events for all textures
// referenced while tracing
dc_.ta->ClearTextures();
LOG_INFO("Begin tracing to %s", filename);
} else {
delete dc_.trace_writer;
dc_.trace_writer = nullptr;
LOG_INFO("End tracing");
}
}
void Emulator::RenderFrame() {
rb_->BeginFrame();
// render the latest tile context
if (TileContext *tactx = dc_.ta->GetLastContext()) {
tile_renderer_->RenderContext(tactx);
return;
}
// render stats
char stats[512];
float speed = *reinterpret_cast<float *>(&speed_);
snprintf(stats, sizeof(stats), "%.2f%%, %.2f rps", speed, dc_.pvr->rps());
rb_->RenderText2D(0, 0, 12.0f, 0xffffffff, stats);
// render profiler
profiler_.Render(rb_);
rb_->EndFrame();
dc_.OnKeyDown(code, value);
}
void Emulator::PumpEvents() {
WindowEvent ev;
window_.PumpEvents();
while (window_.PollEvent(&ev)) {
switch (ev.type) {
case WE_KEY: {
// let the profiler take a stab at the input first
if (!profiler_.HandleInput(ev.key.code, ev.key.value)) {
if (ev.key.code == K_F2) {
if (ev.key.value) {
ToggleTracing();
}
} else {
dc_.maple->HandleInput(0, ev.key.code, ev.key.value);
}
}
} break;
case WE_MOUSEMOVE: {
profiler_.HandleMouseMove(ev.mousemove.x, ev.mousemove.y);
} break;
case WE_RESIZE: {
rb_->ResizeVideo(ev.resize.width, ev.resize.height);
} break;
case WE_QUIT: {
running_ = false;
} break;
}
}
}
void Emulator::OnClose() { running_ = false; }

View File

@ -1,27 +1,20 @@
#ifndef EMULATOR_H
#define EMULATOR_H
#include "emu/profiler.h"
#include "hw/dreamcast.h"
#include "sys/window.h"
#include "ui/window_listener.h"
namespace re {
namespace hw {
namespace holly {
class TileRenderer;
}
}
namespace renderer {
class Backend;
namespace ui {
class Window;
}
namespace emu {
class Emulator {
class Emulator : public ui::WindowListener {
public:
Emulator();
Emulator(ui::Window &window);
~Emulator();
void Run(const char *path);
@ -34,16 +27,13 @@ class Emulator {
bool LoadFlash(const char *path);
bool LaunchBIN(const char *path);
bool LaunchGDI(const char *path);
void ToggleTracing();
void RenderFrame();
void PumpEvents();
sys::Window window_;
Profiler profiler_;
void OnPaint(bool show_main_menu) final;
void OnKeyDown(ui::Keycode code, int16_t value) final;
void OnClose() final;
ui::Window &window_;
hw::Dreamcast dc_;
renderer::Backend *rb_;
hw::holly::TileRenderer *tile_renderer_;
uint32_t speed_;
bool running_;
};
}

View File

@ -1,145 +0,0 @@
#define MICROPROFILE_TEXT_WIDTH 6
#define MICROPROFILE_TEXT_HEIGHT 12
#define MICROPROFILE_WEBSERVER 0
#define MICROPROFILE_GPU_TIMERS 0
#define MICROPROFILE_ENABLED 1
#define MICROPROFILEUI_ENABLED 1
#define MICROPROFILE_IMPL 1
#define MICROPROFILEUI_IMPL 1
#define MICROPROFILE_PER_THREAD_BUFFER_SIZE (1024 * 1024 * 20)
#define MICROPROFILE_CONTEXT_SWITCH_TRACE 0
#include <microprofile.h>
#include <microprofileui.h>
#include <string>
#include "emu/profiler.h"
using namespace re::emu;
using namespace re::renderer;
using namespace re::sys;
static Backend *s_current_backend = nullptr;
static float HueToRGB(float p, float q, float t) {
if (t < 0.0f) {
t += 1.0f;
}
if (t > 1.0f) {
t -= 1.0f;
}
if (t < 1.0f / 6.0f) {
return p + (q - p) * 6.0f * t;
}
if (t < 1.0f / 2.0f) {
return q;
}
if (t < 2.0f / 3.0f) {
return p + (q - p) * (2.0f / 3.0f - t) * 6.0f;
}
return p;
}
static void HSLToRGB(float h, float s, float l, uint8_t *r, uint8_t *g,
uint8_t *b) {
float fr, fg, fb;
if (s == 0.0f) {
fr = fg = fb = l;
} else {
float q = l < 0.5f ? l * (1.0f + s) : l + s - l * s;
float p = 2.0f * l - q;
fr = HueToRGB(p, q, h + 1.0f / 3.0f);
fg = HueToRGB(p, q, h);
fb = HueToRGB(p, q, h - 1.0f / 3.0f);
}
*r = static_cast<uint8_t>(fr * 255);
*g = static_cast<uint8_t>(fg * 255);
*b = static_cast<uint8_t>(fb * 255);
}
Profiler::ThreadScope::ThreadScope(const char *name) {
MicroProfileOnThreadCreate(name);
}
Profiler::ThreadScope::~ThreadScope() { MicroProfileOnThreadExit(); }
uint32_t Profiler::ScopeColor(const char *name) {
auto hash = std::hash<std::string>();
size_t name_hash = hash(std::string(name));
float h = (name_hash % 360) / 360.0f;
float s = 0.7f;
float l = 0.6f;
uint8_t r, g, b;
HSLToRGB(h, s, l, &r, &g, &b);
return (r << 16) | (g << 8) | b;
}
Profiler::Profiler() {
// register and enable gpu and runtime group by default
uint16_t gpu_group = MicroProfileGetGroup("gpu", MicroProfileTokenTypeCpu);
g_MicroProfile.nActiveGroupWanted |= 1ll << gpu_group;
uint16_t runtime_group =
MicroProfileGetGroup("runtime", MicroProfileTokenTypeCpu);
g_MicroProfile.nActiveGroupWanted |= 1ll << runtime_group;
// render time / average time bars by default
g_MicroProfile.nBars |= MP_DRAW_TIMERS | MP_DRAW_AVERAGE | MP_DRAW_CALL_COUNT;
}
bool Profiler::HandleInput(Keycode key, int16_t value) {
if (key == K_F1) {
if (value) {
MicroProfileToggleDisplayMode();
}
return true;
}
if (key == K_MOUSE1) {
MicroProfileMouseButton(value, 0);
return true;
}
if (key == K_MOUSE2) {
MicroProfileMouseButton(0, value);
return true;
}
return false;
}
bool Profiler::HandleMouseMove(int x, int y) {
MicroProfileMousePosition(x, y, 0);
return true;
}
void Profiler::Render(Backend *backend) {
s_current_backend = backend;
MicroProfileFlip();
MicroProfileDraw(s_current_backend->video_width(),
s_current_backend->video_height());
}
//
// microprofile implementation
//
void MicroProfileDrawText(int x, int y, uint32_t color, const char *text,
uint32_t len) {
// microprofile provides 24-bit rgb values for text color
color = 0xff000000 | color;
s_current_backend->RenderText2D(x, y, 12.0f, color, text);
}
void MicroProfileDrawBox(int x0, int y0, int x1, int y1, uint32_t color,
MicroProfileBoxType type) {
// microprofile provides 32-bit argb values for box color, forward straight
// through
s_current_backend->RenderBox2D(x0, y0, x1, y1, color, (BoxType)type);
}
void MicroProfileDrawLine2D(uint32_t num_vertices, float *vertices,
uint32_t color) {
// microprofile provides 24-bit rgb values for line color
color = 0xff000000 | color;
s_current_backend->RenderLine2D(vertices, num_vertices, color);
}

View File

@ -1,43 +1,71 @@
#ifndef PROFILER_H
#define PROFILER_H
#include <string>
#include <microprofile.h>
#include "renderer/backend.h"
#include "sys/keycode.h"
#define PROFILER_SCOPE(group, name) \
MICROPROFILE_SCOPEI(group, name, re::emu::Profiler::ScopeColor(name))
MICROPROFILE_SCOPEI(group, name, re::emu::ScopeColor(name))
#define PROFILER_GPU(name) \
MICROPROFILE_SCOPEI("gpu", name, re::emu::Profiler::ScopeColor(name))
MICROPROFILE_SCOPEI("gpu", name, re::emu::ScopeColor(name))
#define PROFILER_RUNTIME(name) \
MICROPROFILE_SCOPEI("runtime", name, re::emu::Profiler::ScopeColor(name))
MICROPROFILE_SCOPEI("runtime", name, re::emu::ScopeColor(name))
#define PROFILER_COUNT(name, count) MICROPROFILE_COUNTER_SET(name, count)
namespace re {
namespace emu {
class Profiler {
public:
static uint32_t ScopeColor(const char *name);
static inline float HueToRGB(float p, float q, float t) {
if (t < 0.0f) {
t += 1.0f;
}
if (t > 1.0f) {
t -= 1.0f;
}
if (t < 1.0f / 6.0f) {
return p + (q - p) * 6.0f * t;
}
if (t < 1.0f / 2.0f) {
return q;
}
if (t < 2.0f / 3.0f) {
return p + (q - p) * (2.0f / 3.0f - t) * 6.0f;
}
return p;
}
class ThreadScope {
public:
ThreadScope(const char *name);
~ThreadScope();
};
static inline void HSLToRGB(float h, float s, float l, uint8_t *r, uint8_t *g,
uint8_t *b) {
float fr, fg, fb;
Profiler();
if (s == 0.0f) {
fr = fg = fb = l;
} else {
float q = l < 0.5f ? l * (1.0f + s) : l + s - l * s;
float p = 2.0f * l - q;
fr = HueToRGB(p, q, h + 1.0f / 3.0f);
fg = HueToRGB(p, q, h);
fb = HueToRGB(p, q, h - 1.0f / 3.0f);
}
void ThreadCreate(const char *name);
void ThreadExit();
*r = static_cast<uint8_t>(fr * 255);
*g = static_cast<uint8_t>(fg * 255);
*b = static_cast<uint8_t>(fb * 255);
}
bool HandleInput(sys::Keycode key, int16_t value);
bool HandleMouseMove(int x, int y);
void Render(renderer::Backend *backend);
};
static inline uint32_t ScopeColor(const char *name) {
auto hash = std::hash<std::string>();
size_t name_hash = hash(std::string(name));
float h = (name_hash % 360) / 360.0f;
float s = 0.7f;
float l = 0.6f;
uint8_t r, g, b;
HSLToRGB(h, s, l, &r, &g, &b);
return (r << 16) | (g << 8) | b;
}
}
}

View File

@ -2,13 +2,13 @@
#include "emu/tracer.h"
#include "hw/holly/tile_accelerator.h"
#include "hw/holly/trace.h"
#include "renderer/gl_backend.h"
#include "ui/window.h"
using namespace re;
using namespace re::emu;
using namespace re::hw::holly;
using namespace re::renderer;
using namespace re::sys;
using namespace re::ui;
void TraceTextureCache::AddTexture(const TSP &tsp, TCW &tcw,
const uint8_t *palette,
@ -34,31 +34,20 @@ TextureHandle TraceTextureCache::GetTexture(
// register the texture if it hasn't already been
if (!texture.handle) {
// TODO compare tex_it->tsp and tex_it->tcw with incoming?
texture.handle = register_cb(texture.palette, texture.texture);
}
return texture.handle;
}
Tracer::Tracer() {
rb_ = new GLBackend(wnd_);
tile_renderer_ = new TileRenderer(*rb_, texcache_);
current_ctx_ = new TileContext();
Tracer::Tracer(Window &window)
: window_(window), tile_renderer_(*window.render_backend(), texcache_) {
window_.AddListener(this);
}
Tracer::~Tracer() {
delete rb_;
delete tile_renderer_;
delete current_ctx_;
}
Tracer::~Tracer() { window_.RemoveListener(this); }
void Tracer::Run(const char *path) {
if (!Init()) {
LOG_WARNING("Failed to initialize trace viewer");
return;
}
if (!Parse(path)) {
return;
}
@ -66,24 +55,45 @@ void Tracer::Run(const char *path) {
running_ = true;
while (running_) {
PumpEvents();
RenderFrame();
window_.PumpEvents();
}
}
bool Tracer::Init() {
if (!wnd_.Init()) {
return false;
}
void Tracer::OnPaint(bool show_main_menu) {
tile_renderer_.RenderContext(&current_ctx_);
if (!rb_->Init()) {
return false;
}
if (ImGui::Begin("Tracer")) {
int frame = current_cmd_->frame;
return true;
if (ImGui::SliderInt("frame", &frame, 0, num_frames_ - 1)) {
SetFrame(frame);
}
ImGui::Separator();
ImGui::LabelText("autosort", "%d", current_ctx_.autosort);
ImGui::LabelText("texture stride", "%d", current_ctx_.stride);
ImGui::LabelText("palette pixel format", "0x%08x",
current_ctx_.pal_pxl_format);
ImGui::LabelText("bg isp", "0x%08x", current_ctx_.bg_isp.full);
ImGui::LabelText("bg tsp", "0x%08x", current_ctx_.bg_tsp.full);
ImGui::LabelText("bg tcw", "0x%08x", current_ctx_.bg_tcw.full);
ImGui::LabelText("bg depth", "%.2f", current_ctx_.bg_depth);
ImGui::End();
}
}
void Tracer::OnKeyDown(Keycode code, int16_t value) {
if (code == K_LEFT && value) {
SetFrame(current_cmd_->frame - 1);
} else if (code == K_RIGHT && value) {
SetFrame(current_cmd_->frame + 1);
}
}
void Tracer::OnClose() { running_ = false; }
bool Tracer::Parse(const char *path) {
if (!reader_.Parse(path)) {
LOG_WARNING("Failed to parse %s", path);
@ -96,58 +106,19 @@ bool Tracer::Parse(const char *path) {
return false;
}
current_frame_ = 0;
current_cmd_ = nullptr;
NextContext();
SetFrame(0);
return true;
}
void Tracer::PumpEvents() {
WindowEvent ev;
wnd_.PumpEvents();
while (wnd_.PollEvent(&ev)) {
switch (ev.type) {
case WE_KEY: {
if (ev.key.code == K_LEFT && ev.key.value) {
PrevContext();
} else if (ev.key.code == K_RIGHT && ev.key.value) {
NextContext();
}
} break;
case WE_QUIT: {
running_ = false;
} break;
default:
break;
}
}
}
void Tracer::RenderFrame() {
rb_->BeginFrame();
tile_renderer_->RenderContext(current_ctx_);
// render stats
char stats[512];
snprintf(stats, sizeof(stats), "frame %d / %d", current_frame_, num_frames_);
rb_->RenderText2D(0, 0, 12.0f, 0xffffffff, stats);
rb_->EndFrame();
}
int Tracer::GetNumFrames() {
int num_frames = 0;
TraceCommand *cmd = reader_.cmd_head();
while (cmd) {
if (cmd->type == TRACE_RENDER_CONTEXT) {
if (cmd->type == TRACE_CMD_CONTEXT) {
num_frames++;
}
@ -157,86 +128,85 @@ int Tracer::GetNumFrames() {
return num_frames;
}
// Se the current frame to be rendered. Note, due to textures being inserted on
// demand after the render event, the event order will look like so:
// RENDER_CONTEXT frame 0
// INSERT_TEXTURE frame 0
// INSERT_TEXTURE frame 0
// INSERT_TEXTURE frame 0
// RENDER_CONTEXT frame 1
// INSERT_TEXTURE frame 1
// INSERT_TEXTURE frame 1
// RENDER_CONTEXT frame 2
// INSERT_TEXTURE frame 2
void Tracer::SetFrame(int n) {
n = std::max(0, std::min(n, num_frames_ - 1));
// current_cmd_ is either null, or the first command of the current frame
if (!current_cmd_ || n > current_cmd_->frame) {
TraceCommand *next = current_cmd_ ? current_cmd_->next : reader_.cmd_head();
// step forward until all events up to the end of the target frame have
// been processed
while (next && next->frame <= n) {
if (next->type == TRACE_CMD_CONTEXT) {
// track the beginning of the target frame
current_cmd_ = next;
} else if (next->type == TRACE_CMD_TEXTURE) {
texcache_.AddTexture(next->texture.tsp, next->texture.tcw,
next->texture.palette, next->texture.texture);
}
next = next->next;
}
} else if (n < current_cmd_->frame) {
TraceCommand *prev = current_cmd_;
// step backwards until the start of the requested frame
while (prev && prev->frame >= n) {
if (prev->type == TRACE_CMD_CONTEXT) {
// track the beginning of the target frame
current_cmd_ = prev;
} else if (prev->type == TRACE_CMD_TEXTURE) {
// if the texture belongs to a frame after the target frame, remove it
// from the cache and add back the texture it overrode (if it did)
if (prev->frame > n) {
texcache_.RemoveTexture(prev->texture.tsp, prev->texture.tcw);
TraceCommand *override = prev->override;
if (override) {
CHECK_EQ(override->type, TRACE_CMD_TEXTURE);
texcache_.AddTexture(override->texture.tsp, override->texture.tcw,
override->texture.palette,
override->texture.texture);
}
}
}
prev = prev->prev;
}
}
// copy off the render command for the current frame
CopyCommandToContext(current_cmd_, &current_ctx_);
}
// Copy RENDER_CONTEXT command to the current context being rendered.
void Tracer::CopyCommandToContext(const TraceCommand *cmd, TileContext *ctx) {
CHECK_EQ(cmd->type, TRACE_RENDER_CONTEXT);
CHECK_EQ(cmd->type, TRACE_CMD_CONTEXT);
ctx->autosort = cmd->render_context.autosort;
ctx->stride = cmd->render_context.stride;
ctx->pal_pxl_format = cmd->render_context.pal_pxl_format;
ctx->bg_isp = cmd->render_context.bg_isp;
ctx->bg_tsp = cmd->render_context.bg_tsp;
ctx->bg_tcw = cmd->render_context.bg_tcw;
ctx->bg_depth = cmd->render_context.bg_depth;
ctx->video_width = cmd->render_context.video_width;
ctx->video_height = cmd->render_context.video_height;
memcpy(ctx->bg_vertices, cmd->render_context.bg_vertices,
cmd->render_context.bg_vertices_size);
memcpy(ctx->data, cmd->render_context.data, cmd->render_context.data_size);
ctx->size = cmd->render_context.data_size;
}
void Tracer::PrevContext() {
int prev_frame = std::max(1, current_frame_ - 1);
if (prev_frame == current_frame_) {
return;
}
current_cmd_ = current_cmd_->prev;
// scrub through commands until the previous context is reached. for each
// command we move backwards through, re-apply the value it overrode
while (current_cmd_) {
TraceCommand *override = current_cmd_->override;
if (current_cmd_->type == TRACE_INSERT_TEXTURE) {
texcache_.RemoveTexture(current_cmd_->insert_texture.tsp,
current_cmd_->insert_texture.tcw);
if (override) {
CHECK_EQ(override->type, TRACE_INSERT_TEXTURE);
texcache_.AddTexture(
override->insert_texture.tsp, override->insert_texture.tcw,
override->insert_texture.palette, override->insert_texture.texture);
}
} else if (current_cmd_->type == TRACE_RENDER_CONTEXT) {
if (--current_frame_ == prev_frame) {
break;
}
}
current_cmd_ = current_cmd_->prev;
}
CHECK_NOTNULL(current_cmd_);
CopyCommandToContext(current_cmd_, current_ctx_);
}
void Tracer::NextContext() {
int next_frame = std::min(num_frames_, current_frame_ + 1);
if (next_frame == current_frame_) {
return;
}
current_cmd_ = current_cmd_ ? current_cmd_->next : reader_.cmd_head();
while (current_cmd_) {
if (current_cmd_->type == TRACE_INSERT_TEXTURE) {
texcache_.AddTexture(current_cmd_->insert_texture.tsp,
current_cmd_->insert_texture.tcw,
current_cmd_->insert_texture.palette,
current_cmd_->insert_texture.texture);
} else if (current_cmd_->type == TRACE_RENDER_CONTEXT) {
if (++current_frame_ == next_frame) {
break;
}
}
current_cmd_ = current_cmd_->next;
}
CHECK_NOTNULL(current_cmd_);
// render the context
CopyCommandToContext(current_cmd_, current_ctx_);
ctx->autosort = cmd->context.autosort;
ctx->stride = cmd->context.stride;
ctx->pal_pxl_format = cmd->context.pal_pxl_format;
ctx->bg_isp = cmd->context.bg_isp;
ctx->bg_tsp = cmd->context.bg_tsp;
ctx->bg_tcw = cmd->context.bg_tcw;
ctx->bg_depth = cmd->context.bg_depth;
ctx->video_width = cmd->context.video_width;
ctx->video_height = cmd->context.video_height;
memcpy(ctx->bg_vertices, cmd->context.bg_vertices,
cmd->context.bg_vertices_size);
memcpy(ctx->data, cmd->context.data, cmd->context.data_size);
ctx->size = cmd->context.data_size;
}

View File

@ -5,9 +5,14 @@
#include <vector>
#include "hw/holly/tile_renderer.h"
#include "hw/holly/trace.h"
#include "sys/window.h"
#include "ui/window_listener.h"
namespace re {
namespace ui {
class Window;
}
namespace emu {
struct TextureInst {
@ -32,37 +37,33 @@ class TraceTextureCache : public hw::holly::TextureProvider {
std::unordered_map<hw::holly::TextureKey, TextureInst> textures_;
};
class Tracer {
class Tracer : public ui::WindowListener {
public:
Tracer();
Tracer(ui::Window &window);
~Tracer();
void Run(const char *path);
private:
bool Init();
void OnPaint(bool show_main_menu) final;
void OnKeyDown(ui::Keycode code, int16_t value);
void OnClose() final;
bool Parse(const char *path);
void PumpEvents();
void RenderFrame();
int GetNumFrames();
void SetFrame(int n);
void CopyCommandToContext(const hw::holly::TraceCommand *cmd,
hw::holly::TileContext *ctx);
void PrevContext();
void NextContext();
sys::Window wnd_;
ui::Window &window_;
TraceTextureCache texcache_;
renderer::Backend *rb_;
hw::holly::TileRenderer *tile_renderer_;
hw::holly::TileRenderer tile_renderer_;
bool running_;
hw::holly::TraceReader reader_;
hw::holly::TileContext current_ctx_;
hw::holly::TraceCommand *current_cmd_;
int num_frames_;
int current_frame_;
hw::holly::TileContext *current_ctx_;
};
}
}

View File

@ -1,15 +1,11 @@
#ifndef DREAMCAST_H
#define DREAMCAST_H
#include <chrono>
#include "hw/machine.h"
#include "hw/holly/pvr2_regs.h"
#include "hw/holly/pvr2_types.h"
namespace re {
namespace renderer {
class Backend;
}
namespace hw {
namespace aica {
@ -24,7 +20,6 @@ namespace holly {
class Holly;
class PVR2;
class TileAccelerator;
class TraceWriter;
}
namespace maple {
@ -70,7 +65,7 @@ enum {
MEMORY_REGION(MAIN_RAM_4, 0x0f000000, 0x0fffffff),
MEMORY_REGION(AREA4, 0x10000000, 0x13ffffff),
MEMORY_REGION(TA_CMD, 0x10000000, 0x107fffff),
MEMORY_REGION(TA_POLY, 0x10000000, 0x107fffff),
MEMORY_REGION(TA_TEXTURE, 0x11000000, 0x11ffffff),
MEMORY_REGION(AREA5, 0x14000000, 0x17ffffff),
@ -139,8 +134,7 @@ class Dreamcast : public Machine {
holly(nullptr),
maple(nullptr),
pvr(nullptr),
ta(nullptr),
trace_writer(nullptr) {}
ta(nullptr) {}
Register holly_regs[HOLLY_REG_SIZE >> 2];
Register pvr_regs[PVR_REG_SIZE >> 2];
@ -152,7 +146,6 @@ class Dreamcast : public Machine {
hw::maple::Maple *maple;
hw::holly::PVR2 *pvr;
hw::holly::TileAccelerator *ta;
hw::holly::TraceWriter *trace_writer;
#define HOLLY_REG(offset, name, flags, default, type) \
type &name = reinterpret_cast<type &>(holly_regs[name##_OFFSET].value);

View File

@ -11,7 +11,6 @@ using namespace re::hw::gdrom;
using namespace re::hw::holly;
using namespace re::hw::maple;
using namespace re::hw::sh4;
using namespace re::renderer;
using namespace re::sys;
Holly::Holly(Dreamcast *dc) : Device(*dc), MemoryInterface(this), dc_(dc) {}

View File

@ -1,6 +1,7 @@
#include "core/memory.h"
#include "hw/holly/holly.h"
#include "hw/holly/pvr2.h"
#include "hw/holly/pvr2_types.h"
#include "hw/holly/tile_accelerator.h"
#include "hw/dreamcast.h"
#include "hw/memory.h"
@ -15,8 +16,7 @@ PVR2::PVR2(Dreamcast *dc)
MemoryInterface(this),
dc_(dc),
line_timer_(INVALID_TIMER),
current_scanline_(0),
rps_(0.0f) {}
current_scanline_(0) {}
bool PVR2::Init() {
scheduler_ = dc_->scheduler;
@ -72,6 +72,12 @@ void PVR2::WriteRegister(uint32_t addr, uint32_t value) {
uint32_t offset = addr >> 2;
Register &reg = pvr_regs_[offset];
// // forward some reads and writes to the TA
// if (offset >= TA_OL_BASE && offset <= TA_NEXT_OPB_INIT) {
// ta_->ReadRegister(addr);
// return;
// }
if (!(reg.flags & W)) {
LOG_WARNING("Invalid write access at 0x%x", addr);
return;
@ -100,15 +106,6 @@ void PVR2::WriteRegister(uint32_t addr, uint32_t value) {
case STARTRENDER_OFFSET: {
if (value) {
// track render stats
{
auto now = std::chrono::high_resolution_clock::now();
auto delta = std::chrono::duration_cast<std::chrono::nanoseconds>(
now - last_render_);
last_render_ = now;
rps_ = 1000000000.0f / delta.count();
}
ta_->FinalizeContext(dc_->PARAM_BASE.base_address);
}
} break;

View File

@ -2,7 +2,6 @@
#define PVR_CLX2_H
#include <stdint.h>
#include "hw/holly/pvr2_regs.h"
#include "hw/machine.h"
#include "hw/scheduler.h"
@ -21,8 +20,6 @@ class PVR2 : public Device, public MemoryInterface {
public:
PVR2(Dreamcast *dc);
float rps() { return rps_; }
bool Init() final;
protected:
@ -51,9 +48,6 @@ class PVR2 : public Device, public MemoryInterface {
TimerHandle line_timer_;
int line_clock_;
uint32_t current_scanline_;
std::chrono::high_resolution_clock::time_point last_render_;
float rps_;
};
}
}

View File

@ -185,7 +185,6 @@ union TA_ISP_BASE_T {
uint32_t reserved : 8;
};
};
}
}
}

View File

@ -209,8 +209,11 @@ int TileAccelerator::GetVertexType(const PCW &pcw) {
TileAccelerator::TileAccelerator(Dreamcast *dc, Backend *rb)
: Device(*dc),
MemoryInterface(this),
WindowInterface(this),
dc_(dc),
rb_(rb),
tile_renderer_(*rb, *this),
trace_writer_(nullptr),
num_invalidated_(0),
contexts_() {
// initialize context queue
@ -299,10 +302,9 @@ TextureHandle TileAccelerator::GetTexture(const TSP &tsp, const TCW &tcw,
palette, palette_size, &HandlePaletteWrite, this, map_entry);
}
// add insert to trace
if (dc_->trace_writer) {
dc_->trace_writer->WriteInsertTexture(tsp, tcw, palette, palette_size,
texture, texture_size);
if (trace_writer_) {
trace_writer_->WriteInsertTexture(tsp, tcw, palette, palette_size, texture,
texture_size);
}
return handle;
@ -392,14 +394,9 @@ void TileAccelerator::FinalizeContext(uint32_t addr) {
CHECK_NE(it, live_contexts_.end());
TileContext *tactx = it->second;
// save PVR state to context
WritePVRState(tactx);
WriteBackgroundState(tactx);
// add context to trace
if (dc_->trace_writer) {
dc_->trace_writer->WriteRenderContext(tactx);
}
// save required register state being that the actual rendering of this
// context will be deferred
SaveRegisterState(tactx);
// tell holly that rendering is complete
holly_->RequestInterrupt(HOLLY_INTC_PCEOVINT);
@ -411,6 +408,10 @@ void TileAccelerator::FinalizeContext(uint32_t addr) {
// append to the pending queue
pending_contexts_.push(tactx);
if (trace_writer_) {
trace_writer_->WriteRenderContext(tactx);
}
}
TileContext *TileAccelerator::GetLastContext() {
@ -430,49 +431,67 @@ TileContext *TileAccelerator::GetLastContext() {
}
void TileAccelerator::MapPhysicalMemory(Memory &memory, MemoryMap &memmap) {
RegionHandle ta_cmd_handle = memory.AllocRegion(
TA_CMD_START, TA_CMD_SIZE, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, make_delegate(&TileAccelerator::WriteCommand, this), nullptr);
RegionHandle ta_poly_handle = memory.AllocRegion(
TA_POLY_START, TA_POLY_SIZE, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, make_delegate(&TileAccelerator::WritePolyFIFO, this), nullptr);
RegionHandle ta_texture_handle = memory.AllocRegion(
TA_TEXTURE_START, TA_TEXTURE_SIZE, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, make_delegate(&TileAccelerator::WriteTexture, this),
nullptr, nullptr, make_delegate(&TileAccelerator::WriteTextureFIFO, this),
nullptr);
memmap.Mount(ta_cmd_handle, TA_CMD_SIZE, TA_CMD_START);
memmap.Mount(ta_poly_handle, TA_POLY_SIZE, TA_POLY_START);
memmap.Mount(ta_texture_handle, TA_TEXTURE_SIZE, TA_TEXTURE_START);
}
void TileAccelerator::HandleTextureWrite(void *ctx, const Exception &ex,
void *data) {
TileAccelerator *self = reinterpret_cast<TileAccelerator *>(ctx);
TextureCacheMap::value_type *map_entry =
reinterpret_cast<TextureCacheMap::value_type *>(data);
void TileAccelerator::OnPaint(bool show_main_menu) {
// render the latest context
TileContext *tactx = GetLastContext();
// don't double remove the watch during invalidation
TextureEntry &entry = map_entry->second;
entry.texture_watch = nullptr;
if (tactx) {
tile_renderer_.RenderContext(tactx);
}
// add to pending invalidation list (can't remove inside of signal
// handler)
TextureKey texture_key = map_entry->first;
self->pending_invalidations_.insert(texture_key);
if (show_main_menu && ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("TA")) {
if ((!trace_writer_ && ImGui::MenuItem("Start trace")) ||
(trace_writer_ && ImGui::MenuItem("Stop trace"))) {
ToggleTracing();
}
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
}
void TileAccelerator::HandlePaletteWrite(void *ctx, const Exception &ex,
void *data) {
TileAccelerator *self = reinterpret_cast<TileAccelerator *>(ctx);
TextureCacheMap::value_type *map_entry =
reinterpret_cast<TextureCacheMap::value_type *>(data);
void TileAccelerator::ToggleTracing() {
if (!trace_writer_) {
char filename[PATH_MAX];
GetNextTraceFilename(filename, sizeof(filename));
// don't double remove the watch during invalidation
TextureEntry &entry = map_entry->second;
entry.palette_watch = nullptr;
trace_writer_ = new TraceWriter();
// add to pending invalidation list (can't remove inside of signal
// handler)
TextureKey texture_key = map_entry->first;
self->pending_invalidations_.insert(texture_key);
if (!trace_writer_->Open(filename)) {
delete trace_writer_;
trace_writer_ = nullptr;
LOG_INFO("Failed to start tracing");
return;
}
// clear texture cache in order to generate insert events for all textures
// referenced while tracing
ClearTextures();
LOG_INFO("Begin tracing to %s", filename);
} else {
delete trace_writer_;
trace_writer_ = nullptr;
LOG_INFO("End tracing");
}
}
void TileAccelerator::ClearTextures() {
@ -529,17 +548,49 @@ void TileAccelerator::InvalidateTexture(TextureCacheMap::iterator it) {
textures_.erase(it);
}
void TileAccelerator::WriteCommand(uint32_t addr, uint32_t value) {
void TileAccelerator::HandleTextureWrite(void *ctx, const Exception &ex,
void *data) {
TileAccelerator *self = reinterpret_cast<TileAccelerator *>(ctx);
TextureCacheMap::value_type *map_entry =
reinterpret_cast<TextureCacheMap::value_type *>(data);
// don't double remove the watch during invalidation
TextureEntry &entry = map_entry->second;
entry.texture_watch = nullptr;
// add to pending invalidation list (can't remove inside of signal
// handler)
TextureKey texture_key = map_entry->first;
self->pending_invalidations_.insert(texture_key);
}
void TileAccelerator::HandlePaletteWrite(void *ctx, const Exception &ex,
void *data) {
TileAccelerator *self = reinterpret_cast<TileAccelerator *>(ctx);
TextureCacheMap::value_type *map_entry =
reinterpret_cast<TextureCacheMap::value_type *>(data);
// don't double remove the watch during invalidation
TextureEntry &entry = map_entry->second;
entry.palette_watch = nullptr;
// add to pending invalidation list (can't remove inside of signal
// handler)
TextureKey texture_key = map_entry->first;
self->pending_invalidations_.insert(texture_key);
}
void TileAccelerator::WritePolyFIFO(uint32_t addr, uint32_t value) {
WriteContext(dc_->TA_ISP_BASE.base_address, value);
}
void TileAccelerator::WriteTexture(uint32_t addr, uint32_t value) {
void TileAccelerator::WriteTextureFIFO(uint32_t addr, uint32_t value) {
addr &= 0xeeffffff;
re::store(&video_ram_[addr], value);
}
void TileAccelerator::WritePVRState(TileContext *tactx) {
void TileAccelerator::SaveRegisterState(TileContext *tactx) {
// autosort
if (!dc_->FPU_PARAM_CFG.region_header_type) {
tactx->autosort = !dc_->ISP_FEED_CFG.presort;
@ -565,9 +616,7 @@ void TileAccelerator::WritePVRState(TileContext *tactx) {
tactx->video_width = 320;
tactx->video_height = 240;
}
}
void TileAccelerator::WriteBackgroundState(TileContext *tactx) {
// according to the hardware docs, this is the correct calculation of the
// background ISP address. however, in practice, the second TA buffer's ISP
// address comes out to be 0x800000 when booting the bios and the vram is

View File

@ -6,7 +6,9 @@
#include <queue>
#include <unordered_map>
#include "core/interval_tree.h"
#include "hw/holly/tile_accelerator_types.h"
#include "hw/holly/tile_renderer.h"
#include "hw/holly/trace.h"
#include "hw/machine.h"
#include "renderer/backend.h"
#include "sys/memory.h"
@ -21,434 +23,7 @@ namespace holly {
class Holly;
enum {
// control params
TA_PARAM_END_OF_LIST,
TA_PARAM_USER_TILE_CLIP,
TA_PARAM_OBJ_LIST_SET,
TA_PARAM_RESERVED0,
// global params
TA_PARAM_POLY_OR_VOL,
TA_PARAM_SPRITE,
TA_PARAM_RESERVED1,
// vertex params
TA_PARAM_VERTEX,
TA_NUM_PARAMS
};
enum { //
TA_NUM_VERT_TYPES = 18
};
enum {
TA_LIST_OPAQUE,
TA_LIST_OPAQUE_MODVOL,
TA_LIST_TRANSLUCENT,
TA_LIST_TRANSLUCENT_MODVOL,
TA_LIST_PUNCH_THROUGH,
TA_NUM_LISTS
};
enum {
TA_PIXEL_1555,
TA_PIXEL_565,
TA_PIXEL_4444,
TA_PIXEL_YUV422,
TA_PIXEL_BUMPMAP,
TA_PIXEL_4BPP,
TA_PIXEL_8BPP,
TA_PIXEL_RESERVED
};
enum { TA_PAL_ARGB1555, TA_PAL_RGB565, TA_PAL_ARGB4444, TA_PAL_ARGB8888 };
//
//
//
union PCW {
struct {
// obj control
uint32_t uv_16bit : 1;
uint32_t gouraud : 1;
uint32_t offset : 1;
uint32_t texture : 1;
uint32_t col_type : 2;
uint32_t volume : 1;
uint32_t shadow : 1;
uint32_t reserved0 : 8;
// group control
uint32_t user_clip : 2;
uint32_t strip_len : 2;
uint32_t reserved1 : 3;
uint32_t group_en : 1;
// para control
uint32_t list_type : 3;
uint32_t reserved2 : 1;
uint32_t end_of_strip : 1;
uint32_t para_type : 3;
};
uint8_t obj_control;
uint32_t full;
};
// Image Synthesis Processor parameters
union ISP_TSP {
struct {
uint32_t reserved : 20;
uint32_t dcalc_ctrl : 1;
uint32_t cache_bypass : 1;
uint32_t uv_16bit : 1;
uint32_t gouraud_shading : 1;
uint32_t offset : 1;
uint32_t texture : 1;
uint32_t z_write_disable : 1;
uint32_t culling_mode : 2;
uint32_t depth_compare_mode : 3;
};
uint32_t full;
};
// Texture and Shading Processor parameters
union TSP {
struct {
uint32_t texture_v_size : 3;
uint32_t texture_u_size : 3;
uint32_t texture_shading_instr : 2;
uint32_t mipmap_d_adjust : 4;
uint32_t super_sample_texture : 1;
uint32_t filter_mode : 2;
uint32_t clamp_v : 1;
uint32_t clamp_u : 1;
uint32_t flip_v : 1;
uint32_t flip_u : 1;
uint32_t ignore_tex_alpha : 1;
uint32_t use_alpha : 1;
uint32_t color_clamp : 1;
uint32_t fog_control : 2;
uint32_t dst_select : 1;
uint32_t src_select : 1;
uint32_t dst_alpha_instr : 3;
uint32_t src_alpha_instr : 3;
};
uint32_t full;
};
// Texture parameters
union TCW {
// rgb, yuv and bumpmap textures
struct {
uint32_t texture_addr : 21;
uint32_t reserved : 4;
uint32_t stride_select : 1;
uint32_t scan_order : 1;
uint32_t pixel_format : 3;
uint32_t vq_compressed : 1;
uint32_t mip_mapped : 1;
};
// palette textures
struct {
uint32_t texture_addr : 21;
uint32_t palette_selector : 6;
uint32_t pixel_format : 3;
uint32_t vq_compressed : 1;
uint32_t mip_mapped : 1;
} p;
uint32_t full;
};
//
// Global parameters
//
union PolyParam {
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp;
TCW tcw;
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t sdma_data_size;
uint32_t sdma_next_addr;
} type0;
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp;
TCW tcw;
float face_color_a;
float face_color_r;
float face_color_g;
float face_color_b;
} type1;
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp;
TCW tcw;
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t sdma_data_size;
uint32_t sdma_next_addr;
float face_color_a;
float face_color_r;
float face_color_g;
float face_color_b;
float face_offset_color_a;
float face_offset_color_r;
float face_offset_color_g;
float face_offset_color_b;
} type2;
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp0;
TCW tcw0;
TSP tsp1;
TCW tcw1;
uint32_t sdma_data_size;
uint32_t sdma_next_addr;
} type3;
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp0;
TCW tcw0;
TSP tsp1;
TCW tcw1;
uint32_t sdma_data_size;
uint32_t sdma_next_addr;
float face_color_a_0;
float face_color_r_0;
float face_color_g_0;
float face_color_b_0;
float face_color_a_1;
float face_color_r_1;
float face_color_g_1;
float face_color_b_1;
} type4;
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp;
TCW tcw;
uint32_t base_color;
uint32_t offset_color;
uint32_t sdma_data_size;
uint32_t sdma_next_addr;
} sprite;
struct {
PCW pcw;
ISP_TSP isp_tsp;
uint32_t reserved[6];
} modvol;
};
//
// Vertex parameters
//
union VertexParam {
struct {
PCW pcw;
float xyz[3];
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t base_color;
uint32_t ignore_2;
} type0;
struct {
PCW pcw;
float xyz[3];
float base_color_a;
float base_color_r;
float base_color_g;
float base_color_b;
} type1;
struct {
PCW pcw;
float xyz[3];
uint32_t ignore_0;
uint32_t ignore_1;
float base_intensity;
uint32_t ignore_2;
} type2;
struct {
PCW pcw;
float xyz[3];
float uv[2];
uint32_t base_color;
uint32_t offset_color;
} type3;
struct {
PCW pcw;
float xyz[3];
uint16_t uv[2];
uint32_t ignore_0;
uint32_t base_color;
uint32_t offset_color;
} type4;
struct {
PCW pcw;
float xyz[3];
float uv[2];
uint32_t ignore_0;
uint32_t ignore_1;
float base_color_a;
float base_color_r;
float base_color_g;
float base_color_b;
float offset_color_a;
float offset_color_r;
float offset_color_g;
float offset_color_b;
} type5;
struct {
PCW pcw;
float xyz[3];
uint16_t uv[2];
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t ignore_2;
float base_color_a;
float base_color_r;
float base_color_g;
float base_color_b;
float offset_color_a;
float offset_color_r;
float offset_color_g;
float offset_color_b;
} type6;
struct {
PCW pcw;
float xyz[3];
float uv[2];
float base_intensity;
float offset_intensity;
} type7;
struct {
PCW pcw;
float xyz[3];
uint16_t uv[2];
uint32_t ignore_0;
float base_intensity;
float offset_intensity;
} type8;
struct {
PCW pcw;
float xyz[3];
uint32_t base_color_0;
uint32_t base_color_1;
uint32_t ignore_0;
uint32_t ignore_1;
} type9;
struct {
PCW pcw;
float xyz[3];
float base_intensity_0;
float base_intensity_1;
uint32_t ignore_0;
uint32_t ignore_1;
} type10;
struct {
PCW pcw;
float xyz[3];
float uv_0[2];
uint32_t base_color_0;
uint32_t offset_color_0;
float uv_1[2];
uint32_t base_color_1;
uint32_t offset_color_1;
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t ignore_2;
uint32_t ignore_3;
} type11;
struct {
PCW pcw;
float xyz[3];
uint16_t vu_0[2];
uint32_t ignore_0;
uint32_t base_color_0;
uint32_t offset_color_0;
uint16_t vu_1[2];
uint32_t ignore_1;
uint32_t base_color_1;
uint32_t offset_color_1;
uint32_t ignore_2;
uint32_t ignore_3;
uint32_t ignore_4;
uint32_t ignore_5;
} type12;
struct {
PCW pcw;
float xyz[3];
float uv_0[2];
float base_intensity_0;
float offset_intensity_0;
float uv_1[2];
float base_intensity_1;
float offset_intensity_1;
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t ignore_2;
uint32_t ignore_3;
} type13;
struct {
PCW pcw;
float xyz[3];
uint16_t vu_0[2];
uint32_t ignore_0;
float base_intensity_0;
float offset_intensity_0;
uint16_t vu_1[2];
uint32_t ignore_1;
float base_intensity_1;
float offset_intensity_1;
uint32_t ignore_2;
uint32_t ignore_3;
uint32_t ignore_4;
uint32_t ignore_5;
} type14;
struct {
PCW pcw;
float xyz[4][3];
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t ignore_2;
} sprite0;
struct {
PCW pcw;
float xyz[4][3];
uint32_t uv[3];
} sprite1;
};
enum {
MAX_CONTEXTS = 8,
// worst case background vertex size, see ISP_BACKGND_T field
BG_VERTEX_SIZE = (0b111 * 2 + 3) * 4 * 3
};
static const int MAX_CONTEXTS = 8;
struct TextureEntry;
typedef std::unordered_map<TextureKey, TextureEntry> TextureCacheMap;
@ -463,39 +38,15 @@ struct TextureEntry {
sys::WatchHandle palette_watch;
};
struct TileContext {
uint32_t addr;
// pvr state
bool autosort;
int stride;
int pal_pxl_format;
int video_width;
int video_height;
ISP_TSP bg_isp;
TSP bg_tsp;
TCW bg_tcw;
float bg_depth;
uint8_t bg_vertices[BG_VERTEX_SIZE];
// command buffer
uint8_t data[0x100000];
int cursor;
int size;
// current global state
const PolyParam *last_poly;
const VertexParam *last_vertex;
int list_type;
int vertex_type;
};
typedef std::unordered_map<TextureKey, TileContext *> TileContextMap;
typedef std::queue<TileContext *> TileContextQueue;
class TileAccelerator : public Device,
public MemoryInterface,
public WindowInterface,
public TextureProvider {
friend class PVR2;
public:
static int GetParamSize(const PCW &pcw, int vertex_type);
static int GetPolyType(const PCW &pcw);
@ -507,7 +58,6 @@ class TileAccelerator : public Device,
renderer::TextureHandle GetTexture(const TSP &tsp, const TCW &tcw,
RegisterTextureCallback register_cb) final;
void ClearTextures();
void SoftReset();
void InitContext(uint32_t addr);
@ -516,29 +66,36 @@ class TileAccelerator : public Device,
TileContext *GetLastContext();
protected:
// MemoryInterface
void MapPhysicalMemory(Memory &memory, MemoryMap &memmap) final;
// WindowInterface
void OnPaint(bool show_main_menu) final;
private:
void ToggleTracing();
void ClearTextures();
void ClearPendingTextures();
void InvalidateTexture(TextureKey key);
void InvalidateTexture(TextureCacheMap::iterator it);
static void HandleTextureWrite(void *ctx, const sys::Exception &ex,
void *data);
static void HandlePaletteWrite(void *ctx, const sys::Exception &ex,
void *data);
void ClearPendingTextures();
void InvalidateTexture(TextureKey key);
void InvalidateTexture(TextureCacheMap::iterator it);
void WritePolyFIFO(uint32_t addr, uint32_t value);
void WriteTextureFIFO(uint32_t addr, uint32_t value);
void WriteCommand(uint32_t addr, uint32_t value);
void WriteTexture(uint32_t addr, uint32_t value);
void WritePVRState(TileContext *tactx);
void WriteBackgroundState(TileContext *tactx);
void SaveRegisterState(TileContext *tactx);
Dreamcast *dc_;
renderer::Backend *rb_;
Memory *memory_;
holly::Holly *holly_;
uint8_t *video_ram_;
hw::holly::TileRenderer tile_renderer_;
TraceWriter *trace_writer_;
TextureCacheMap textures_;
TextureSet pending_invalidations_;

View File

@ -0,0 +1,466 @@
#ifndef TILE_ACCELERATOR_TYPES_H
#define TILE_ACCELERATOR_TYPES_H
namespace re {
namespace hw {
namespace holly {
enum {
// control params
TA_PARAM_END_OF_LIST,
TA_PARAM_USER_TILE_CLIP,
TA_PARAM_OBJ_LIST_SET,
TA_PARAM_RESERVED0,
// global params
TA_PARAM_POLY_OR_VOL,
TA_PARAM_SPRITE,
TA_PARAM_RESERVED1,
// vertex params
TA_PARAM_VERTEX,
TA_NUM_PARAMS
};
enum { //
TA_NUM_VERT_TYPES = 18
};
enum {
TA_LIST_OPAQUE,
TA_LIST_OPAQUE_MODVOL,
TA_LIST_TRANSLUCENT,
TA_LIST_TRANSLUCENT_MODVOL,
TA_LIST_PUNCH_THROUGH,
TA_NUM_LISTS
};
enum {
TA_PIXEL_1555,
TA_PIXEL_565,
TA_PIXEL_4444,
TA_PIXEL_YUV422,
TA_PIXEL_BUMPMAP,
TA_PIXEL_4BPP,
TA_PIXEL_8BPP,
TA_PIXEL_RESERVED
};
enum {
TA_PAL_ARGB1555,
TA_PAL_RGB565,
TA_PAL_ARGB4444,
TA_PAL_ARGB8888,
};
union PCW {
struct {
// obj control
uint32_t uv_16bit : 1;
uint32_t gouraud : 1;
uint32_t offset : 1;
uint32_t texture : 1;
uint32_t col_type : 2;
uint32_t volume : 1;
uint32_t shadow : 1;
uint32_t reserved0 : 8;
// group control
uint32_t user_clip : 2;
uint32_t strip_len : 2;
uint32_t reserved1 : 3;
uint32_t group_en : 1;
// para control
uint32_t list_type : 3;
uint32_t reserved2 : 1;
uint32_t end_of_strip : 1;
uint32_t para_type : 3;
};
uint8_t obj_control;
uint32_t full;
};
// Image Synthesis Processor parameters
union ISP_TSP {
struct {
uint32_t reserved : 20;
uint32_t dcalc_ctrl : 1;
uint32_t cache_bypass : 1;
uint32_t uv_16bit : 1;
uint32_t gouraud_shading : 1;
uint32_t offset : 1;
uint32_t texture : 1;
uint32_t z_write_disable : 1;
uint32_t culling_mode : 2;
uint32_t depth_compare_mode : 3;
};
uint32_t full;
};
// Texture and Shading Processor parameters
union TSP {
struct {
uint32_t texture_v_size : 3;
uint32_t texture_u_size : 3;
uint32_t texture_shading_instr : 2;
uint32_t mipmap_d_adjust : 4;
uint32_t super_sample_texture : 1;
uint32_t filter_mode : 2;
uint32_t clamp_v : 1;
uint32_t clamp_u : 1;
uint32_t flip_v : 1;
uint32_t flip_u : 1;
uint32_t ignore_tex_alpha : 1;
uint32_t use_alpha : 1;
uint32_t color_clamp : 1;
uint32_t fog_control : 2;
uint32_t dst_select : 1;
uint32_t src_select : 1;
uint32_t dst_alpha_instr : 3;
uint32_t src_alpha_instr : 3;
};
uint32_t full;
};
// Texture parameters
union TCW {
// rgb, yuv and bumpmap textures
struct {
uint32_t texture_addr : 21;
uint32_t reserved : 4;
uint32_t stride_select : 1;
uint32_t scan_order : 1;
uint32_t pixel_format : 3;
uint32_t vq_compressed : 1;
uint32_t mip_mapped : 1;
};
// palette textures
struct {
uint32_t texture_addr : 21;
uint32_t palette_selector : 6;
uint32_t pixel_format : 3;
uint32_t vq_compressed : 1;
uint32_t mip_mapped : 1;
} p;
uint32_t full;
};
//
// Global parameters
//
union PolyParam {
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp;
TCW tcw;
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t sdma_data_size;
uint32_t sdma_next_addr;
} type0;
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp;
TCW tcw;
float face_color_a;
float face_color_r;
float face_color_g;
float face_color_b;
} type1;
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp;
TCW tcw;
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t sdma_data_size;
uint32_t sdma_next_addr;
float face_color_a;
float face_color_r;
float face_color_g;
float face_color_b;
float face_offset_color_a;
float face_offset_color_r;
float face_offset_color_g;
float face_offset_color_b;
} type2;
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp0;
TCW tcw0;
TSP tsp1;
TCW tcw1;
uint32_t sdma_data_size;
uint32_t sdma_next_addr;
} type3;
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp0;
TCW tcw0;
TSP tsp1;
TCW tcw1;
uint32_t sdma_data_size;
uint32_t sdma_next_addr;
float face_color_a_0;
float face_color_r_0;
float face_color_g_0;
float face_color_b_0;
float face_color_a_1;
float face_color_r_1;
float face_color_g_1;
float face_color_b_1;
} type4;
struct {
PCW pcw;
ISP_TSP isp_tsp;
TSP tsp;
TCW tcw;
uint32_t base_color;
uint32_t offset_color;
uint32_t sdma_data_size;
uint32_t sdma_next_addr;
} sprite;
struct {
PCW pcw;
ISP_TSP isp_tsp;
uint32_t reserved[6];
} modvol;
};
//
// Vertex parameters
//
union VertexParam {
struct {
PCW pcw;
float xyz[3];
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t base_color;
uint32_t ignore_2;
} type0;
struct {
PCW pcw;
float xyz[3];
float base_color_a;
float base_color_r;
float base_color_g;
float base_color_b;
} type1;
struct {
PCW pcw;
float xyz[3];
uint32_t ignore_0;
uint32_t ignore_1;
float base_intensity;
uint32_t ignore_2;
} type2;
struct {
PCW pcw;
float xyz[3];
float uv[2];
uint32_t base_color;
uint32_t offset_color;
} type3;
struct {
PCW pcw;
float xyz[3];
uint16_t uv[2];
uint32_t ignore_0;
uint32_t base_color;
uint32_t offset_color;
} type4;
struct {
PCW pcw;
float xyz[3];
float uv[2];
uint32_t ignore_0;
uint32_t ignore_1;
float base_color_a;
float base_color_r;
float base_color_g;
float base_color_b;
float offset_color_a;
float offset_color_r;
float offset_color_g;
float offset_color_b;
} type5;
struct {
PCW pcw;
float xyz[3];
uint16_t uv[2];
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t ignore_2;
float base_color_a;
float base_color_r;
float base_color_g;
float base_color_b;
float offset_color_a;
float offset_color_r;
float offset_color_g;
float offset_color_b;
} type6;
struct {
PCW pcw;
float xyz[3];
float uv[2];
float base_intensity;
float offset_intensity;
} type7;
struct {
PCW pcw;
float xyz[3];
uint16_t uv[2];
uint32_t ignore_0;
float base_intensity;
float offset_intensity;
} type8;
struct {
PCW pcw;
float xyz[3];
uint32_t base_color_0;
uint32_t base_color_1;
uint32_t ignore_0;
uint32_t ignore_1;
} type9;
struct {
PCW pcw;
float xyz[3];
float base_intensity_0;
float base_intensity_1;
uint32_t ignore_0;
uint32_t ignore_1;
} type10;
struct {
PCW pcw;
float xyz[3];
float uv_0[2];
uint32_t base_color_0;
uint32_t offset_color_0;
float uv_1[2];
uint32_t base_color_1;
uint32_t offset_color_1;
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t ignore_2;
uint32_t ignore_3;
} type11;
struct {
PCW pcw;
float xyz[3];
uint16_t vu_0[2];
uint32_t ignore_0;
uint32_t base_color_0;
uint32_t offset_color_0;
uint16_t vu_1[2];
uint32_t ignore_1;
uint32_t base_color_1;
uint32_t offset_color_1;
uint32_t ignore_2;
uint32_t ignore_3;
uint32_t ignore_4;
uint32_t ignore_5;
} type12;
struct {
PCW pcw;
float xyz[3];
float uv_0[2];
float base_intensity_0;
float offset_intensity_0;
float uv_1[2];
float base_intensity_1;
float offset_intensity_1;
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t ignore_2;
uint32_t ignore_3;
} type13;
struct {
PCW pcw;
float xyz[3];
uint16_t vu_0[2];
uint32_t ignore_0;
float base_intensity_0;
float offset_intensity_0;
uint16_t vu_1[2];
uint32_t ignore_1;
float base_intensity_1;
float offset_intensity_1;
uint32_t ignore_2;
uint32_t ignore_3;
uint32_t ignore_4;
uint32_t ignore_5;
} type14;
struct {
PCW pcw;
float xyz[4][3];
uint32_t ignore_0;
uint32_t ignore_1;
uint32_t ignore_2;
} sprite0;
struct {
PCW pcw;
float xyz[4][3];
uint32_t uv[3];
} sprite1;
};
// worst case background vertex size, see ISP_BACKGND_T field
static const int BG_VERTEX_SIZE = (0b111 * 2 + 3) * 4 * 3;
struct TileContext {
uint32_t addr;
// pvr state
bool autosort;
int stride;
int pal_pxl_format;
int video_width;
int video_height;
ISP_TSP bg_isp;
TSP bg_tsp;
TCW bg_tcw;
float bg_depth;
uint8_t bg_vertices[BG_VERTEX_SIZE];
// command buffer
uint8_t data[0x100000];
int cursor;
int size;
// current global state
const PolyParam *last_poly;
const VertexParam *last_vertex;
int list_type;
int vertex_type;
};
}
}
}
#endif

View File

@ -38,7 +38,10 @@ class TextureProvider {
// parsing it and ultimately rendering it out to the supplied backend. This
// is split out of the main TileAccelerator code so it can be re-used by
// Tracer.
enum { MAX_SURFACES = 0x10000, MAX_VERTICES = 0x10000 };
enum {
MAX_SURFACES = 0x10000,
MAX_VERTICES = 0x10000,
};
class TileRenderer {
public:

View File

@ -1,5 +1,6 @@
#include <unordered_map>
#include "core/assert.h"
#include "hw/holly/tile_accelerator.h"
#include "hw/holly/trace.h"
#include "sys/filesystem.h"
@ -49,6 +50,10 @@ bool TraceReader::Parse(const char *filename) {
return false;
}
if (!PatchFrames()) {
return false;
}
return true;
}
@ -81,18 +86,18 @@ bool TraceReader::PatchPointers() {
// patch relative data pointers
switch (curr_cmd->type) {
case TRACE_INSERT_TEXTURE: {
curr_cmd->insert_texture.palette += reinterpret_cast<intptr_t>(ptr);
curr_cmd->insert_texture.texture += reinterpret_cast<intptr_t>(ptr);
ptr += sizeof(*curr_cmd) + curr_cmd->insert_texture.palette_size +
curr_cmd->insert_texture.texture_size;
case TRACE_CMD_TEXTURE: {
curr_cmd->texture.palette += reinterpret_cast<intptr_t>(ptr);
curr_cmd->texture.texture += reinterpret_cast<intptr_t>(ptr);
ptr += sizeof(*curr_cmd) + curr_cmd->texture.palette_size +
curr_cmd->texture.texture_size;
} break;
case TRACE_RENDER_CONTEXT: {
curr_cmd->render_context.bg_vertices += reinterpret_cast<intptr_t>(ptr);
curr_cmd->render_context.data += reinterpret_cast<intptr_t>(ptr);
ptr += sizeof(*curr_cmd) + curr_cmd->render_context.bg_vertices_size +
curr_cmd->render_context.data_size;
case TRACE_CMD_CONTEXT: {
curr_cmd->context.bg_vertices += reinterpret_cast<intptr_t>(ptr);
curr_cmd->context.data += reinterpret_cast<intptr_t>(ptr);
ptr += sizeof(*curr_cmd) + curr_cmd->context.bg_vertices_size +
curr_cmd->context.data_size;
} break;
default:
@ -113,26 +118,17 @@ bool TraceReader::PatchOverrides() {
std::unordered_map<TextureKey, TraceCommand *> last_inserts;
while (cmd) {
switch (cmd->type) {
case TRACE_INSERT_TEXTURE: {
TextureKey texture_key = TextureProvider::GetTextureKey(
cmd->insert_texture.tsp, cmd->insert_texture.tcw);
auto last_insert = last_inserts.find(texture_key);
if (cmd->type == TRACE_CMD_TEXTURE) {
TextureKey texture_key =
TextureProvider::GetTextureKey(cmd->texture.tsp, cmd->texture.tcw);
auto last_insert = last_inserts.find(texture_key);
if (last_insert != last_inserts.end()) {
cmd->override = last_insert->second;
last_insert->second = cmd;
} else {
last_inserts.insert(std::make_pair(texture_key, cmd));
}
} break;
case TRACE_RENDER_CONTEXT: {
} break;
default:
LOG_INFO("Unexpected trace command type %d", cmd->type);
return false;
if (last_insert != last_inserts.end()) {
cmd->override = last_insert->second;
last_insert->second = cmd;
} else {
last_inserts.insert(std::make_pair(texture_key, cmd));
}
}
cmd = cmd->next;
@ -141,6 +137,24 @@ bool TraceReader::PatchOverrides() {
return true;
}
// Patch in frame numbers to ease working with the trace.
bool TraceReader::PatchFrames() {
TraceCommand *cmd = cmd_head();
int frame = -1;
while (cmd) {
if (cmd->type == TRACE_CMD_CONTEXT) {
frame++;
}
cmd->frame = frame;
cmd = cmd->next;
}
return true;
}
TraceWriter::TraceWriter() : file_(nullptr) {}
TraceWriter::~TraceWriter() { Close(); }
@ -163,13 +177,13 @@ void TraceWriter::WriteInsertTexture(const TSP &tsp, const TCW &tcw,
const uint8_t *palette, int palette_size,
const uint8_t *texture, int texture_size) {
TraceCommand cmd;
cmd.type = TRACE_INSERT_TEXTURE;
cmd.insert_texture.tsp = tsp;
cmd.insert_texture.tcw = tcw;
cmd.insert_texture.palette_size = palette_size;
cmd.insert_texture.palette = reinterpret_cast<const uint8_t *>(sizeof(cmd));
cmd.insert_texture.texture_size = texture_size;
cmd.insert_texture.texture =
cmd.type = TRACE_CMD_TEXTURE;
cmd.texture.tsp = tsp;
cmd.texture.tcw = tcw;
cmd.texture.palette_size = palette_size;
cmd.texture.palette = reinterpret_cast<const uint8_t *>(sizeof(cmd));
cmd.texture.texture_size = texture_size;
cmd.texture.texture =
reinterpret_cast<const uint8_t *>(sizeof(cmd) + palette_size);
CHECK_EQ(fwrite(&cmd, sizeof(cmd), 1, file_), 1);
@ -183,21 +197,20 @@ void TraceWriter::WriteInsertTexture(const TSP &tsp, const TCW &tcw,
void TraceWriter::WriteRenderContext(TileContext *tactx) {
TraceCommand cmd;
cmd.type = TRACE_RENDER_CONTEXT;
cmd.render_context.autosort = tactx->autosort;
cmd.render_context.stride = tactx->stride;
cmd.render_context.pal_pxl_format = tactx->pal_pxl_format;
cmd.render_context.video_width = tactx->video_width;
cmd.render_context.video_height = tactx->video_height;
cmd.render_context.bg_isp = tactx->bg_isp;
cmd.render_context.bg_tsp = tactx->bg_tsp;
cmd.render_context.bg_tcw = tactx->bg_tcw;
cmd.render_context.bg_depth = tactx->bg_depth;
cmd.render_context.bg_vertices_size = sizeof(tactx->bg_vertices);
cmd.render_context.bg_vertices =
reinterpret_cast<const uint8_t *>(sizeof(cmd));
cmd.render_context.data_size = tactx->size;
cmd.render_context.data = reinterpret_cast<const uint8_t *>(
cmd.type = TRACE_CMD_CONTEXT;
cmd.context.autosort = tactx->autosort;
cmd.context.stride = tactx->stride;
cmd.context.pal_pxl_format = tactx->pal_pxl_format;
cmd.context.video_width = tactx->video_width;
cmd.context.video_height = tactx->video_height;
cmd.context.bg_isp = tactx->bg_isp;
cmd.context.bg_tsp = tactx->bg_tsp;
cmd.context.bg_tcw = tactx->bg_tcw;
cmd.context.bg_depth = tactx->bg_depth;
cmd.context.bg_vertices_size = sizeof(tactx->bg_vertices);
cmd.context.bg_vertices = reinterpret_cast<const uint8_t *>(sizeof(cmd));
cmd.context.data_size = tactx->size;
cmd.context.data = reinterpret_cast<const uint8_t *>(
sizeof(cmd) + sizeof(tactx->bg_vertices));
CHECK_EQ(fwrite(&cmd, sizeof(cmd), 1, file_), 1);

View File

@ -1,16 +1,25 @@
#ifndef TRACE_H
#define TRACE_H
#include "hw/holly/tile_accelerator.h"
#include "hw/holly/tile_accelerator_types.h"
namespace re {
namespace hw {
namespace holly {
enum TraceCommandType { TRACE_INSERT_TEXTURE, TRACE_RENDER_CONTEXT };
enum TraceCommandType {
TRACE_CMD_NONE,
TRACE_CMD_TEXTURE,
TRACE_CMD_CONTEXT,
};
struct TraceCommand {
TraceCommand() : prev(nullptr), next(nullptr), override(nullptr) {}
TraceCommand()
: type(TRACE_CMD_NONE),
prev(nullptr),
next(nullptr),
override(nullptr),
frame(0) {}
TraceCommandType type;
@ -18,6 +27,7 @@ struct TraceCommand {
TraceCommand *prev;
TraceCommand *next;
TraceCommand *override;
int frame;
// the data pointers in these structs are written out relative to the cmd,
// and patched to absolute pointers on read
@ -29,7 +39,7 @@ struct TraceCommand {
const uint8_t *palette;
uint32_t texture_size;
const uint8_t *texture;
} insert_texture;
} texture;
// slimmed down version of the TileContext structure, will need to be in
// sync
@ -47,7 +57,7 @@ struct TraceCommand {
const uint8_t *bg_vertices;
uint32_t data_size;
const uint8_t *data;
} render_context;
} context;
};
};
@ -65,6 +75,7 @@ class TraceReader {
private:
void Reset();
bool PatchPointers();
bool PatchFrames();
bool PatchOverrides();
size_t trace_size_;

View File

@ -6,6 +6,7 @@
using namespace re;
using namespace re::hw;
using namespace re::ui;
DEFINE_bool(debug, false, "Run debug server");
@ -15,8 +16,10 @@ ExecuteInterface::ExecuteInterface(Device *device) { device->execute_ = this; }
MemoryInterface::MemoryInterface(Device *device) { device->memory_ = this; }
WindowInterface::WindowInterface(Device *device) { device->window_ = this; }
Device::Device(Machine &machine)
: debug_(nullptr), execute_(nullptr), memory_(nullptr) {
: debug_(nullptr), execute_(nullptr), memory_(nullptr), window_(nullptr) {
machine.devices.push_back(this);
}
@ -65,3 +68,23 @@ void Machine::Tick(const std::chrono::nanoseconds &delta) {
scheduler->Tick(delta);
}
}
void Machine::OnPaint(bool show_main_menu) {
for (auto device : devices) {
if (!device->window()) {
continue;
}
device->window()->OnPaint(show_main_menu);
}
}
void Machine::OnKeyDown(Keycode code, int16_t value) {
for (auto device : devices) {
if (!device->window()) {
continue;
}
device->window()->OnKeyDown(code, value);
}
}

View File

@ -3,6 +3,7 @@
#include <chrono>
#include <vector>
#include "ui/window.h"
namespace re {
namespace hw {
@ -47,10 +48,20 @@ class MemoryInterface {
virtual void MapVirtualMemory(Memory &memory, MemoryMap &memmap) {}
};
class WindowInterface {
public:
WindowInterface(Device *device);
virtual ~WindowInterface() = default;
virtual void OnPaint(bool show_main_menu){};
virtual void OnKeyDown(ui::Keycode code, int16_t value){};
};
class Device {
friend class DebugInterface;
friend class ExecuteInterface;
friend class MemoryInterface;
friend class WindowInterface;
public:
virtual ~Device() = default;
@ -58,6 +69,7 @@ class Device {
DebugInterface *debug() { return debug_; }
ExecuteInterface *execute() { return execute_; }
MemoryInterface *memory() { return memory_; }
WindowInterface *window() { return window_; }
Device(Machine &machine);
@ -67,6 +79,7 @@ class Device {
DebugInterface *debug_;
ExecuteInterface *execute_;
MemoryInterface *memory_;
WindowInterface *window_;
};
class Machine {
@ -81,7 +94,10 @@ class Machine {
bool Init();
void Suspend();
void Resume();
void Tick(const std::chrono::nanoseconds &delta);
void OnPaint(bool show_main_menu);
void OnKeyDown(ui::Keycode code, int16_t value);
Debugger *debugger;
Memory *memory;

View File

@ -9,9 +9,10 @@ using namespace re::hw;
using namespace re::hw::holly;
using namespace re::hw::maple;
using namespace re::hw::sh4;
using namespace re::sys;
using namespace re::ui;
Maple::Maple(Dreamcast *dc) : Device(*dc), dc_(dc), devices_() {
Maple::Maple(Dreamcast *dc)
: Device(*dc), WindowInterface(this), dc_(dc), devices_() {
// default controller device
devices_[0] = std::unique_ptr<MapleController>(new MapleController());
}
@ -24,15 +25,6 @@ bool Maple::Init() {
return true;
}
bool Maple::HandleInput(int port, Keycode key, int16_t value) {
CHECK_LT(port, MAX_PORTS);
std::unique_ptr<MapleDevice> &dev = devices_[port];
if (!dev) {
return false;
}
return dev->HandleInput(key, value);
}
// The controller can be started up by two methods: by software, or by hardware
// in synchronization with the V-BLANK signal. These methods are selected
// through the trigger selection register (SB_MDTSEL).
@ -47,6 +39,16 @@ void Maple::VBlank() {
// TODO maple vblank interrupt?
}
void Maple::OnKeyDown(Keycode key, int16_t value) {
std::unique_ptr<MapleDevice> &dev = devices_[0];
if (!dev) {
return;
}
dev->HandleInput(key, value);
}
template uint8_t Maple::ReadRegister(uint32_t addr);
template uint16_t Maple::ReadRegister(uint32_t addr);
template uint32_t Maple::ReadRegister(uint32_t addr);

View File

@ -3,7 +3,7 @@
#include <memory>
#include "hw/machine.h"
#include "sys/keycode.h"
#include "ui/keycode.h"
namespace re {
namespace hw {
@ -17,8 +17,6 @@ class Memory;
namespace maple {
enum { MAX_PORTS = 4 };
enum MapleFunction {
FN_CONTROLLER = 0x01000000,
FN_MEMORYCARD = 0x02000000,
@ -92,15 +90,17 @@ struct MapleFrame {
uint32_t params[0xff];
};
static const int MAX_PORTS = 4;
class MapleDevice {
public:
virtual ~MapleDevice() {}
virtual bool HandleInput(sys::Keycode key, int16_t value) = 0;
virtual bool HandleInput(ui::Keycode key, int16_t value) = 0;
virtual bool HandleFrame(const MapleFrame &frame, MapleFrame &res) = 0;
};
class Maple : public Device {
class Maple : public Device, public WindowInterface {
friend class holly::Holly;
public:
@ -108,9 +108,11 @@ class Maple : public Device {
bool Init() final;
bool HandleInput(int port, sys::Keycode key, int16_t value);
void VBlank();
private:
void OnKeyDown(ui::Keycode code, int16_t value) final;
private:
template <typename T>
T ReadRegister(uint32_t addr);

View File

@ -5,9 +5,9 @@
#include "core/log.h"
#include "hw/maple/maple_controller.h"
using namespace re::hw::maple;
using namespace re::sys;
using namespace json11;
using namespace re::hw::maple;
using namespace re::ui;
DEFINE_string(profile, "", "Controller profile");

View File

@ -48,19 +48,19 @@ class MapleControllerProfile {
void Load(const char *path);
int LookupButton(sys::Keycode code) { return button_map_[code]; }
int LookupButton(ui::Keycode code) { return button_map_[code]; }
private:
void MapKey(const char *name, int button);
int button_map_[sys::K_NUM_KEYS];
int button_map_[ui::K_NUM_KEYS];
};
class MapleController : public MapleDevice {
public:
MapleController();
bool HandleInput(sys::Keycode key, int16_t value);
bool HandleInput(ui::Keycode key, int16_t value);
bool HandleFrame(const MapleFrame &frame, MapleFrame &res);
private:

View File

@ -1,3 +1,4 @@
#include <imgui.h>
#include "core/math.h"
#include "core/memory.h"
#include "emu/profiler.h"
@ -8,7 +9,6 @@
#include "hw/scheduler.h"
using namespace re;
using namespace re::emu;
using namespace re::hw;
using namespace re::hw::sh4;
using namespace re::jit;
@ -34,8 +34,12 @@ SH4::SH4(Dreamcast *dc)
DebugInterface(this),
ExecuteInterface(this),
MemoryInterface(this),
WindowInterface(this),
dc_(dc),
code_cache_(nullptr),
show_perf_(false),
mips_(),
num_mips_(0),
requested_interrupts_(0),
pending_interrupts_(0),
tmu_timers_{INVALID_TIMER, INVALID_TIMER, INVALID_TIMER},
@ -93,9 +97,9 @@ void SH4::Run(const std::chrono::nanoseconds &delta) {
s_current_cpu = this;
// each block's epilog will decrement the remaining cycles as they run
ctx_.remaining_cycles = cycles;
ctx_.num_cycles = cycles;
while (ctx_.remaining_cycles > 0) {
while (ctx_.num_cycles > 0) {
SH4BlockEntry *block = code_cache_->GetBlock(ctx_.pc);
block->run();
@ -103,6 +107,21 @@ void SH4::Run(const std::chrono::nanoseconds &delta) {
CheckPendingInterrupts();
}
// track mips
auto now = std::chrono::high_resolution_clock::now();
auto next_time = last_mips_time_ + std::chrono::seconds(1);
if (now > next_time) {
auto delta = std::chrono::duration_cast<std::chrono::nanoseconds>(
now - last_mips_time_);
auto delta_f =
std::chrono::duration_cast<std::chrono::duration<float>>(delta).count();
auto delta_scaled = delta_f * 1000000.0f;
mips_[num_mips_++ % MAX_MIPS_SAMPLES] = ctx_.num_instrs / delta_scaled;
ctx_.num_instrs = 0;
last_mips_time_ = now;
}
s_current_cpu = nullptr;
}
@ -288,6 +307,40 @@ void SH4::MapVirtualMemory(Memory &memory, MemoryMap &memmap) {
memmap.Mount(sh4_sq_handle, SH4_SQ_SIZE, SH4_SQ_START);
}
void SH4::OnPaint(bool show_main_menu) {
if (show_main_menu && ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("CPU")) {
ImGui::MenuItem("Perf", "", &show_perf_);
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
if (show_perf_) {
ImGui::Begin("Perf", nullptr, ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_AlwaysAutoResize);
ImGui::SetWindowPos(ImVec2(
ImGui::GetIO().DisplaySize.x - ImGui::GetWindowSize().x - 10, 10));
// calculate average mips
float avg_mips = 0.0f;
for (int i = std::max(0, num_mips_ - MAX_MIPS_SAMPLES); i < num_mips_;
i++) {
avg_mips += mips_[i % MAX_MIPS_SAMPLES];
}
avg_mips /= std::max(std::min(num_mips_, MAX_MIPS_SAMPLES), 1);
char overlay_text[128];
snprintf(overlay_text, sizeof(overlay_text), "%.2f", avg_mips);
ImGui::PlotLines("MIPS", mips_, MAX_MIPS_SAMPLES, num_mips_, overlay_text,
0.0f, 400.0f);
ImGui::End();
}
}
void SH4::CompilePC() {
SH4CodeCache *code_cache = s_current_cpu->code_cache_;
SH4Context *ctx = &s_current_cpu->ctx_;
@ -305,7 +358,7 @@ void SH4::InvalidInstruction(SH4Context *ctx, uint64_t data) {
CHECK_NE(it, self->breakpoints_.end());
// force the main loop to break
self->ctx_.remaining_cycles = 0;
self->ctx_.num_cycles = 0;
// let the debugger know execution has stopped
self->dc_->debugger->Trap();

View File

@ -1,9 +1,9 @@
#ifndef SH4_H
#define SH4_H
#include <chrono>
#include "hw/sh4/sh4_code_cache.h"
#include "hw/sh4/sh4_int.h"
#include "hw/sh4/sh4_regs.h"
#include "hw/sh4/sh4_types.h"
#include "hw/machine.h"
#include "hw/scheduler.h"
#include "jit/frontend/sh4/sh4_context.h"
@ -17,15 +17,18 @@ class Dreamcast;
namespace sh4 {
static const int MAX_MIPS_SAMPLES = 10;
enum DDTRW {
DDT_R,
DDT_W
DDT_W,
};
class SH4 : public Device,
public DebugInterface,
public ExecuteInterface,
public MemoryInterface {
public MemoryInterface,
public WindowInterface {
friend void RunSH4Test(const SH4Test &);
public:
@ -58,6 +61,9 @@ class SH4 : public Device,
void MapPhysicalMemory(Memory &memory, MemoryMap &memmap) final;
void MapVirtualMemory(Memory &memory, MemoryMap &memmap) final;
// WindowInterface
void OnPaint(bool show_main_menu) final;
private:
static void CompilePC();
static void InvalidInstruction(jit::frontend::sh4::SH4Context *ctx,
@ -114,6 +120,14 @@ class SH4 : public Device,
#include "hw/sh4/sh4_regs.inc"
#undef SH4_REG
uint32_t area7_[0x4000]; // consolidated, 16kb area 7 memory
uint8_t cache_[0x2000]; // 8kb cache
bool show_perf_;
std::chrono::high_resolution_clock::time_point last_mips_time_;
float mips_[MAX_MIPS_SAMPLES];
int num_mips_;
Interrupt sorted_interrupts_[NUM_INTERRUPTS];
uint64_t sort_id_[NUM_INTERRUPTS];
uint64_t priority_mask_[16];
@ -122,9 +136,6 @@ class SH4 : public Device,
hw::TimerHandle tmu_timers_[3];
TimerDelegate tmu_delegates_[3];
uint32_t area7_[0x4000]; // consolidated, 16kb area 7 memory
uint8_t cache_[0x2000]; // 8kb cache
};
}
}

View File

@ -1,23 +0,0 @@
#ifndef SH4_INT_H
#define SH4_INT_H
namespace re {
namespace hw {
namespace sh4 {
struct InterruptInfo {
int intevt, default_priority, ipr, ipr_shift;
};
enum Interrupt {
#define SH4_INT(name, intevt, pri, ipr, ipr_shift) SH4_INTC_##name,
#include "hw/sh4/sh4_int.inc"
#undef SH4_INT
NUM_INTERRUPTS
};
}
}
}
#endif

View File

@ -7,6 +7,7 @@ namespace re {
namespace hw {
namespace sh4 {
// registers
static const uint32_t UNDEFINED = 0x0;
static const uint32_t HELD = 0x1;
@ -78,6 +79,17 @@ enum {
#undef SH4_REG
};
// interrupts
enum Interrupt {
#define SH4_INT(name, intevt, pri, ipr, ipr_shift) SH4_INTC_##name,
#include "hw/sh4/sh4_int.inc"
#undef SH4_INT
NUM_INTERRUPTS
};
struct InterruptInfo {
int intevt, default_priority, ipr, ipr_shift;
};
}
}
}

View File

@ -94,10 +94,16 @@ void SH4Builder::Emit(uint32_t start_addr, int max_instrs) {
// emit block epilog
current_instr_ = tail_instr->prev();
Value *remaining_cycles =
LoadContext(offsetof(SH4Context, remaining_cycles), VALUE_I32);
remaining_cycles = Sub(remaining_cycles, AllocConstant(guest_cycles_));
StoreContext(offsetof(SH4Context, remaining_cycles), remaining_cycles);
// update remaining cycles
Value *num_cycles = LoadContext(offsetof(SH4Context, num_cycles), VALUE_I32);
num_cycles = Sub(num_cycles, AllocConstant(guest_cycles_));
StoreContext(offsetof(SH4Context, num_cycles), num_cycles);
// update num instructions
int sh4_num_instrs = (pc_ - start_addr) >> 1;
Value *num_instrs = LoadContext(offsetof(SH4Context, num_instrs), VALUE_I32);
num_instrs = Add(num_instrs, AllocConstant(sh4_num_instrs));
StoreContext(offsetof(SH4Context, num_instrs), num_instrs);
}
Value *SH4Builder::LoadRegister(int n, ValueType type) {

View File

@ -39,7 +39,11 @@ struct SH4Context {
void (*SRUpdated)(SH4Context *, uint64_t old_sr);
void (*FPSCRUpdated)(SH4Context *, uint64_t old_fpscr);
int32_t remaining_cycles;
// the main dispatch loop is ran until num_cycles is <= 0
int32_t num_cycles;
// used for debug performance monitoring
uint32_t num_instrs;
uint32_t pc, pr, sr, sr_qm, fpscr;
uint32_t dbr, gbr, vbr;

View File

@ -1,15 +1,18 @@
#include <stdio.h>
#include <memory>
#include <gflags/gflags.h>
#include "core/log.h"
#include "emu/emulator.h"
#include "emu/tracer.h"
#include "sys/exception_handler.h"
#include "sys/filesystem.h"
#include "sys/network.h"
#include "ui/window.h"
using namespace re;
using namespace re::emu;
using namespace re::sys;
using namespace re::ui;
void InitFlags(int *argc, char ***argv) {
const char *appdir = GetAppDir();
@ -47,12 +50,19 @@ int main(int argc, char **argv) {
return EXIT_FAILURE;
}
Window window;
if (!window.Init()) {
LOG_WARNING("Failed to initialize window");
return EXIT_FAILURE;
}
const char *load = argc > 1 ? argv[1] : nullptr;
if (load && strstr(load, ".trace")) {
std::unique_ptr<Tracer> tracer(new Tracer());
std::unique_ptr<Tracer> tracer(new Tracer(window));
tracer->Run(load);
} else {
std::unique_ptr<Emulator> emu(new Emulator());
std::unique_ptr<Emulator> emu(new Emulator(window));
emu->Run(load);
}

View File

@ -10,21 +10,22 @@ typedef int TextureHandle;
enum PixelFormat {
PXL_INVALID,
PXL_RGBA,
PXL_RGBA5551,
PXL_RGB565,
PXL_RGBA4444,
PXL_RGBA8888
PXL_RGBA8888,
};
enum FilterMode { //
enum FilterMode {
FILTER_NEAREST,
FILTER_BILINEAR
FILTER_BILINEAR,
};
enum WrapMode { //
enum WrapMode {
WRAP_REPEAT,
WRAP_CLAMP_TO_EDGE,
WRAP_MIRRORED_REPEAT
WRAP_MIRRORED_REPEAT,
};
enum DepthFunc {
@ -36,13 +37,13 @@ enum DepthFunc {
DEPTH_GREATER,
DEPTH_NEQUAL,
DEPTH_GEQUAL,
DEPTH_ALWAYS
DEPTH_ALWAYS,
};
enum CullFace {
CULL_NONE, //
CULL_NONE,
CULL_FRONT,
CULL_BACK
CULL_BACK,
};
enum BlendFunc {
@ -56,17 +57,25 @@ enum BlendFunc {
BLEND_DST_ALPHA,
BLEND_ONE_MINUS_DST_ALPHA,
BLEND_DST_COLOR,
BLEND_ONE_MINUS_DST_COLOR
BLEND_ONE_MINUS_DST_COLOR,
};
enum ShadeMode {
SHADE_DECAL,
SHADE_MODULATE,
SHADE_DECAL_ALPHA,
SHADE_MODULATE_ALPHA
SHADE_MODULATE_ALPHA,
};
enum BoxType { BOX_BAR, BOX_FLAT };
enum BoxType {
BOX_BAR,
BOX_FLAT,
};
enum PrimativeType {
PRIM_TRIANGLES,
PRIM_LINES,
};
struct Vertex {
float xyz[3];
@ -89,16 +98,19 @@ struct Surface {
};
struct Vertex2D {
float x, y;
float xy[2];
float uv[2];
uint32_t color;
float u, v;
};
struct Surface2D {
int prim_type;
int texture;
PrimativeType prim_type;
TextureHandle texture;
BlendFunc src_blend;
BlendFunc dst_blend;
bool scissor;
float scissor_rect[4];
int first_vert;
int num_verts;
};
@ -106,13 +118,8 @@ class Backend {
public:
virtual ~Backend() {}
virtual int video_width() = 0;
virtual int video_height() = 0;
virtual bool Init() = 0;
virtual void ResizeVideo(int width, int height) = 0;
virtual TextureHandle RegisterTexture(PixelFormat format, FilterMode filter,
WrapMode wrap_u, WrapMode wrap_v,
bool gen_mipmaps, int width, int height,
@ -120,16 +127,20 @@ class Backend {
virtual void FreeTexture(TextureHandle handle) = 0;
virtual void BeginFrame() = 0;
virtual void RenderText2D(int x, int y, float point_size, uint32_t color,
const char *text) = 0;
virtual void RenderBox2D(int x0, int y0, int x1, int y1, uint32_t color,
BoxType type) = 0;
virtual void RenderLine2D(float *verts, int num_verts, uint32_t color) = 0;
virtual void EndFrame() = 0;
virtual void Begin2D() = 0;
virtual void End2D() = 0;
virtual void BeginSurfaces2D(const Vertex2D *verts, int num_verts,
uint16_t *indices, int num_indices) = 0;
virtual void DrawSurface2D(const Surface2D &surf) = 0;
virtual void EndSurfaces2D() = 0;
virtual void RenderSurfaces(const Eigen::Matrix4f &projection,
const Surface *surfs, int num_surfs,
const Vertex *verts, int num_verts,
const int *sorted_surfs) = 0;
virtual void EndFrame() = 0;
};
}
}

View File

@ -1,27 +1,14 @@
#include <memory>
#include "core/assert.h"
#include "emu/profiler.h"
#include "renderer/gl_backend.h"
#define STB_TRUETYPE_IMPLEMENTATION
#include <stb_truetype.h>
using namespace re;
using namespace re::renderer;
using namespace re::sys;
using namespace re::ui;
#include "inconsolata_ttf.inc"
#include "renderer/ta.glsl"
#include "renderer/ui.glsl"
#define Q0(d, member, v) d[0].member = v
#define Q1(d, member, v) \
d[1].member = v; \
d[3].member = v
#define Q2(d, member, v) d[4].member = v
#define Q3(d, member, v) \
d[2].member = v; \
d[5].member = v
static GLenum filter_funcs[] = {
GL_NEAREST, // FILTER_NEAREST
GL_LINEAR, // FILTER_BILINEAR
@ -65,19 +52,23 @@ static GLenum blend_funcs[] = {GL_NONE,
GL_DST_COLOR,
GL_ONE_MINUS_DST_COLOR};
static GLenum prim_types[] = {
GL_TRIANGLES, // PRIM_TRIANGLES
GL_LINES, // PRIM_LINES
};
GLBackend::GLBackend(Window &window)
: window_(window),
ctx_(nullptr),
textures_{0},
num_verts2d_(0),
num_surfs2d_(0) {}
: window_(window), ctx_(nullptr), textures_{0} {
window_.AddListener(this);
}
GLBackend::~GLBackend() {
DestroyFonts();
DestroyVertexBuffers();
DestroyShaders();
DestroyTextures();
DestroyContext();
window_.RemoveListener(this);
}
bool GLBackend::Init() {
@ -88,16 +79,10 @@ bool GLBackend::Init() {
CreateTextures();
CreateShaders();
CreateVertexBuffers();
SetupDefaultState();
return true;
}
void GLBackend::ResizeVideo(int width, int height) {
state_.video_width = width;
state_.video_height = height;
}
TextureHandle GLBackend::RegisterTexture(PixelFormat format, FilterMode filter,
WrapMode wrap_u, WrapMode wrap_v,
bool gen_mipmaps, int width,
@ -114,6 +99,10 @@ TextureHandle GLBackend::RegisterTexture(PixelFormat format, FilterMode filter,
GLuint internal_fmt;
GLuint pixel_fmt;
switch (format) {
case PXL_RGBA:
internal_fmt = GL_RGBA;
pixel_fmt = GL_UNSIGNED_BYTE;
break;
case PXL_RGBA5551:
internal_fmt = GL_RGBA;
pixel_fmt = GL_UNSIGNED_SHORT_5_5_5_1;
@ -162,160 +151,94 @@ void GLBackend::FreeTexture(TextureHandle handle) {
}
void GLBackend::BeginFrame() {
int width = window_.width();
int height = window_.height();
SetDepthMask(true);
glViewport(0, 0, state_.video_width, state_.video_height);
glScissor(0, 0, state_.video_width, state_.video_height);
glViewport(0, 0, width, height);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void GLBackend::RenderText2D(int x, int y, float point_size, uint32_t color,
const char *text) {
float fx = (float)x;
float fy = (float)y;
const BakedFont *font = GetFont(point_size);
void GLBackend::EndFrame() { SDL_GL_SwapWindow(window_.handle()); }
int len = (int)strlen(text);
Vertex2D *vert =
AllocVertices2D({GL_TRIANGLES, (int)font->texture, BLEND_SRC_ALPHA,
BLEND_ONE_MINUS_SRC_ALPHA, 0},
6 * len);
void GLBackend::Begin2D() {
Eigen::Matrix4f ortho = Eigen::Matrix4f::Identity();
ortho(0, 0) = 2.0f / (float)window_.width();
ortho(1, 1) = -2.0f / (float)window_.height();
ortho(0, 3) = -1.0;
ortho(1, 3) = 1.0;
ortho(2, 2) = 0;
// convert color from argb -> abgr
color = (color & 0xff000000) | ((color & 0xff) << 16) | (color & 0xff00) |
((color & 0xff0000) >> 16);
Eigen::Matrix4f projection = ortho.transpose();
// stbtt_GetPackedQuad treats the y parameter as the character's baseline.
// however, the incoming y represents the top of the text. offset it by the
// font's ascent (distance from top -> baseline) to compensate
fy += font->ascent;
SetDepthMask(false);
SetDepthFunc(DEPTH_NONE);
SetCullFace(CULL_NONE);
while (*text) {
if (*text >= 32 /* && *text < 128*/) {
stbtt_aligned_quad q;
stbtt_GetPackedQuad(&font->chars[0], font->tw, font->th, *text, &fx, &fy,
&q, 0);
Q0(vert, x, q.x0);
Q0(vert, y, q.y0);
Q0(vert, color, color);
Q0(vert, u, q.s0);
Q0(vert, v, q.t0);
Q1(vert, x, q.x1);
Q1(vert, y, q.y0);
Q1(vert, color, color);
Q1(vert, u, q.s1);
Q1(vert, v, q.t0);
Q2(vert, x, q.x1);
Q2(vert, y, q.y1);
Q2(vert, color, color);
Q2(vert, u, q.s1);
Q2(vert, v, q.t1);
Q3(vert, x, q.x0);
Q3(vert, y, q.y1);
Q3(vert, color, color);
Q3(vert, u, q.s0);
Q3(vert, v, q.t1);
vert += 6;
}
++text;
}
BindVAO(ui_vao_);
BindProgram(&ui_program_);
glUniformMatrix4fv(GetUniform(UNIFORM_MODELVIEWPROJECTIONMATRIX), 1, GL_FALSE,
projection.data());
glUniform1i(GetUniform(UNIFORM_DIFFUSEMAP), MAP_DIFFUSE);
}
void GLBackend::RenderBox2D(int x0, int y0, int x1, int y1, uint32_t color,
BoxType type) {
Vertex2D *vertex = AllocVertices2D(
{GL_TRIANGLES, 0, BLEND_SRC_ALPHA, BLEND_ONE_MINUS_SRC_ALPHA, 0}, 6);
void GLBackend::End2D() { SetScissorTest(false); }
if (type == BOX_FLAT) {
CHECK(x0 <= x1);
CHECK(y0 <= y1);
void GLBackend::BeginSurfaces2D(const Vertex2D *verts, int num_verts,
uint16_t *indices, int num_indices) {
glBindBuffer(GL_ARRAY_BUFFER, ui_vbo_);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex2D) * num_verts, verts,
GL_DYNAMIC_DRAW);
// convert color from argb -> abgr
color = (color & 0xff000000) | ((color & 0xff) << 16) | (color & 0xff00) |
((color & 0xff0000) >> 16);
Q0(vertex, x, (float)x0);
Q0(vertex, y, (float)y0);
Q0(vertex, color, color);
Q1(vertex, x, (float)x1);
Q1(vertex, y, (float)y0);
Q1(vertex, color, color);
Q2(vertex, x, (float)x1);
Q2(vertex, y, (float)y1);
Q2(vertex, color, color);
Q3(vertex, x, (float)x0);
Q3(vertex, y, (float)y1);
Q3(vertex, color, color);
if (indices) {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ui_ibo_);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint16_t) * num_indices,
indices, GL_DYNAMIC_DRAW);
ui_use_ibo_ = true;
} else {
uint32_t a = (color & 0xff000000) >> 24;
uint32_t r = (color & 0xff0000) >> 16;
uint32_t g = (color & 0xff00) >> 8;
uint32_t b = color & 0xff;
uint32_t max = std::max(std::max(std::max(r, g), b), 30u);
uint32_t min = std::min(std::min(std::min(r, g), b), 180u);
uint32_t r0 = 0xff & ((r + max) / 2);
uint32_t g0 = 0xff & ((g + max) / 2);
uint32_t b0 = 0xff & ((b + max) / 2);
uint32_t r1 = 0xff & ((r + min) / 2);
uint32_t g1 = 0xff & ((g + min) / 2);
uint32_t b1 = 0xff & ((b + min) / 2);
uint32_t color0 = (a << 24) | (b0 << 16) | (g0 << 8) | r0;
uint32_t color1 = (a << 24) | (b1 << 16) | (g1 << 8) | r1;
Q0(vertex, x, (float)x0);
Q0(vertex, y, (float)y0);
Q0(vertex, color, color0);
Q1(vertex, x, (float)x1);
Q1(vertex, y, (float)y0);
Q1(vertex, color, color0);
Q2(vertex, x, (float)x1);
Q2(vertex, y, (float)y1);
Q2(vertex, color, color1);
Q3(vertex, x, (float)x0);
Q3(vertex, y, (float)y1);
Q3(vertex, color, color1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, -1);
ui_use_ibo_ = false;
}
}
void GLBackend::RenderLine2D(float *verts, int num_verts, uint32_t color) {
if (!num_verts) {
return;
void GLBackend::DrawSurface2D(const Surface2D &surf) {
if (surf.scissor) {
SetScissorTest(true);
SetScissorClip(static_cast<int>(surf.scissor_rect[0]),
static_cast<int>(surf.scissor_rect[1]),
static_cast<int>(surf.scissor_rect[2]),
static_cast<int>(surf.scissor_rect[3]));
} else {
SetScissorTest(false);
}
Vertex2D *vertex = AllocVertices2D(
{GL_LINES, 0, BLEND_SRC_ALPHA, BLEND_ONE_MINUS_SRC_ALPHA, 0},
2 * (num_verts - 1));
SetBlendFunc(surf.src_blend, surf.dst_blend);
BindTexture(MAP_DIFFUSE, surf.texture ? textures_[surf.texture] : white_tex_);
// convert color from argb -> abgr
color = (color & 0xff000000) | ((color & 0xff) << 16) | (color & 0xff00) |
((color & 0xff0000) >> 16);
for (int i = 0; i < num_verts - 1; ++i) {
vertex[0].x = verts[i * 2];
vertex[0].y = verts[i * 2 + 1];
vertex[0].color = color;
vertex[1].x = verts[(i + 1) * 2];
vertex[1].y = verts[(i + 1) * 2 + 1];
vertex[1].color = color;
vertex += 2;
if (ui_use_ibo_) {
glDrawElements(
prim_types[surf.prim_type], surf.num_verts, GL_UNSIGNED_SHORT,
reinterpret_cast<void *>(sizeof(uint16_t) * surf.first_vert));
} else {
glDrawArrays(prim_types[surf.prim_type], surf.first_vert, surf.num_verts);
}
}
void GLBackend::EndSurfaces2D() {}
void GLBackend::RenderSurfaces(const Eigen::Matrix4f &projection,
const Surface *surfs, int num_surfs,
const Vertex *verts, int num_verts,
const int *sorted_surfs) {
PROFILER_GPU("GLBackend::RenderSurfaces");
if (state_.debug_wireframe) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
// transpose to column-major for OpenGL
Eigen::Matrix4f transposed = projection.transpose();
@ -343,12 +266,21 @@ void GLBackend::RenderSurfaces(const Eigen::Matrix4f &projection,
surf->texture ? textures_[surf->texture] : white_tex_);
glDrawArrays(GL_TRIANGLE_STRIP, surf->first_vert, surf->num_verts);
}
if (state_.debug_wireframe) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
}
void GLBackend::EndFrame() {
Flush2D();
void GLBackend::OnPaint(bool show_main_menu) {
if (show_main_menu && ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("Render")) {
ImGui::MenuItem("Wireframe", "", &state_.debug_wireframe);
ImGui::EndMenu();
}
SDL_GL_SwapWindow(window_.handle());
ImGui::EndMainMenuBar();
}
}
bool GLBackend::InitContext() {
@ -378,10 +310,6 @@ bool GLBackend::InitContext() {
// enable vsync
SDL_GL_SetSwapInterval(1);
// set default width / height
state_.video_width = window_.width();
state_.video_height = window_.height();
return true;
}
@ -450,20 +378,23 @@ void GLBackend::CreateVertexBuffers() {
glGenBuffers(1, &ui_vbo_);
glBindBuffer(GL_ARRAY_BUFFER, ui_vbo_);
glGenBuffers(1, &ui_ibo_);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ui_ibo_);
// xy
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
(void *)offsetof(Vertex2D, x));
// color
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex2D),
(void *)offsetof(Vertex2D, color));
(void *)offsetof(Vertex2D, xy));
// texcoord
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
(void *)offsetof(Vertex2D, uv));
// color
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
(void *)offsetof(Vertex2D, u));
glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex2D),
(void *)offsetof(Vertex2D, color));
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
@ -507,6 +438,7 @@ void GLBackend::DestroyVertexBuffers() {
return;
}
glDeleteBuffers(1, &ui_ibo_);
glDeleteBuffers(1, &ui_vbo_);
glDeleteVertexArrays(1, &ui_vao_);
@ -514,22 +446,29 @@ void GLBackend::DestroyVertexBuffers() {
glDeleteVertexArrays(1, &ta_vao_);
}
void GLBackend::DestroyFonts() {
if (!ctx_) {
void GLBackend::SetScissorTest(bool enabled) {
if (state_.scissor_test == enabled) {
return;
}
for (auto it : fonts_) {
delete it.second;
state_.scissor_test = enabled;
if (enabled) {
glEnable(GL_SCISSOR_TEST);
} else {
glDisable(GL_SCISSOR_TEST);
}
}
void GLBackend::SetupDefaultState() { glEnable(GL_SCISSOR_TEST); }
void GLBackend::SetScissorClip(int x, int y, int width, int height) {
glScissor(x, y, width, height);
}
void GLBackend::SetDepthMask(bool enabled) {
if (state_.depth_mask == enabled) {
return;
}
state_.depth_mask = enabled;
glDepthMask(enabled ? 1 : 0);
@ -539,6 +478,7 @@ void GLBackend::SetDepthFunc(DepthFunc fn) {
if (state_.depth_func == fn) {
return;
}
state_.depth_func = fn;
if (fn == DEPTH_NONE) {
@ -553,6 +493,7 @@ void GLBackend::SetCullFace(CullFace fn) {
if (state_.cull_face == fn) {
return;
}
state_.cull_face = fn;
if (fn == CULL_NONE) {
@ -567,6 +508,7 @@ void GLBackend::SetBlendFunc(BlendFunc src_fn, BlendFunc dst_fn) {
if (state_.src_blend == src_fn && state_.dst_blend == dst_fn) {
return;
}
state_.src_blend = src_fn;
state_.dst_blend = dst_fn;
@ -582,7 +524,9 @@ void GLBackend::BindVAO(GLuint vao) {
if (state_.current_vao == vao) {
return;
}
state_.current_vao = vao;
glBindVertexArray(vao);
}
@ -590,7 +534,9 @@ void GLBackend::BindProgram(ShaderProgram *program) {
if (state_.current_program == program) {
return;
}
state_.current_program = program;
glUseProgram(program ? program->program : 0);
}
@ -602,138 +548,3 @@ void GLBackend::BindTexture(TextureMap map, GLuint tex) {
GLint GLBackend::GetUniform(UniformAttr attr) {
return state_.current_program->uniforms[attr];
}
const BakedFont *GLBackend::GetFont(float point_size) {
static const int FONT_TEXTURE_SIZE = 512;
static const unsigned char *ttf_data = inconsolata_ttf;
auto it = fonts_.find(point_size);
if (it != fonts_.end()) {
return it->second;
}
std::unique_ptr<BakedFont> font(new BakedFont());
font->tw = FONT_TEXTURE_SIZE;
font->th = FONT_TEXTURE_SIZE;
// load the font ourself in order to get the ascent info
stbtt_fontinfo f;
if (!stbtt_InitFont(&f, ttf_data, 0)) {
LOG_WARNING("Failed to initialize font");
return nullptr;
}
int ascent;
stbtt_GetFontVMetrics(&f, &ascent, nullptr, nullptr);
font->ascent = (float)ascent * stbtt_ScaleForPixelHeight(&f, point_size);
// bake the font into the bitmap
unsigned char bitmap[FONT_TEXTURE_SIZE * FONT_TEXTURE_SIZE];
stbtt_pack_context pc;
stbtt_PackBegin(&pc, bitmap, FONT_TEXTURE_SIZE, FONT_TEXTURE_SIZE, 0, 1,
NULL);
stbtt_PackSetOversampling(&pc, 2, 2);
if (!stbtt_PackFontRange(&pc, ttf_data, 0, point_size, 32, 127,
font->chars + 32)) {
LOG_WARNING("Failed to pack font");
return nullptr;
}
stbtt_PackEnd(&pc);
// generate gl texture for bitmap
GLuint texid;
glGenTextures(1, &texid);
glBindTexture(GL_TEXTURE_2D, texid);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLint swizzle_mask[] = {GL_ONE, GL_ONE, GL_ONE, GL_RED};
glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzle_mask);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, FONT_TEXTURE_SIZE, FONT_TEXTURE_SIZE, 0,
GL_RED, GL_UNSIGNED_BYTE, bitmap);
glBindTexture(GL_TEXTURE_2D, 0);
font->texture = texid;
// insert into cache (map now takes ownership)
auto pair = fonts_.insert(std::make_pair(point_size, font.release()));
CHECK(pair.second);
return (pair.first)->second;
}
Eigen::Matrix4f GLBackend::Ortho2D() {
Eigen::Matrix4f p = Eigen::Matrix4f::Identity();
p(0, 0) = 2.0f / (float)state_.video_width;
p(1, 1) = -2.0f / (float)state_.video_height;
p(0, 3) = -1.0;
p(1, 3) = 1.0;
p(2, 2) = 0;
return p;
}
Vertex2D *GLBackend::AllocVertices2D(const Surface2D &desc, int count) {
if (num_verts2d_ + count > MAX_2D_VERTICES) {
Flush2D();
}
CHECK(num_verts2d_ + count <= MAX_2D_VERTICES);
uint32_t first_vert = num_verts2d_;
num_verts2d_ += count;
// try to batch with the last surface if possible
if (num_surfs2d_) {
Surface2D &last_surf = surfs2d_[num_surfs2d_ - 1];
if (last_surf.prim_type == desc.prim_type &&
last_surf.texture == desc.texture &&
last_surf.src_blend == desc.src_blend &&
last_surf.dst_blend == desc.dst_blend) {
last_surf.num_verts += count;
return &verts2d_[first_vert];
}
}
// else, allocate a new surface
CHECK(num_surfs2d_ < MAX_2D_SURFACES);
Surface2D &next_surf = surfs2d_[num_surfs2d_];
next_surf.prim_type = desc.prim_type;
next_surf.texture = desc.texture;
next_surf.src_blend = desc.src_blend;
next_surf.dst_blend = desc.dst_blend;
next_surf.num_verts = count;
num_surfs2d_++;
return &verts2d_[first_vert];
}
void GLBackend::Flush2D() {
if (!num_surfs2d_) {
return;
}
Eigen::Matrix4f ortho = Ortho2D();
Eigen::Matrix4f projection = ortho.transpose();
glBindBuffer(GL_ARRAY_BUFFER, ui_vbo_);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex2D) * num_verts2d_, verts2d_,
GL_DYNAMIC_DRAW);
SetDepthMask(false);
SetDepthFunc(DEPTH_NONE);
SetCullFace(CULL_NONE);
BindVAO(ui_vao_);
BindProgram(&ui_program_);
glUniformMatrix4fv(GetUniform(UNIFORM_MODELVIEWPROJECTIONMATRIX), 1, GL_FALSE,
projection.data());
glUniform1i(GetUniform(UNIFORM_DIFFUSEMAP), MAP_DIFFUSE);
int offset = 0;
for (int i = 0; i < num_surfs2d_; ++i) {
int count = surfs2d_[i].num_verts;
BindTexture(MAP_DIFFUSE,
surfs2d_[i].texture ? surfs2d_[i].texture : white_tex_);
SetBlendFunc(surfs2d_[i].src_blend, surfs2d_[i].dst_blend);
glDrawArrays(surfs2d_[i].prim_type, offset, count);
offset += count;
}
num_verts2d_ = 0;
num_surfs2d_ = 0;
}

View File

@ -3,36 +3,25 @@
#include <GL/glew.h>
#include <SDL_opengl.h>
#include <stb_truetype.h>
#include <unordered_map>
#include "renderer/backend.h"
#include "renderer/gl_shader.h"
#include "sys/window.h"
#include "ui/window.h"
namespace re {
namespace renderer {
enum { //
enum {
MAX_TEXTURES = 1024,
MAX_2D_VERTICES = 16384,
MAX_2D_SURFACES = 256
};
enum TextureMap { //
MAP_DIFFUSE
};
struct BakedFont {
int tw, th;
float ascent;
stbtt_packedchar chars[0xff];
intptr_t texture;
enum TextureMap {
MAP_DIFFUSE,
};
struct BackendState {
BackendState()
: video_width(0),
video_height(0),
: debug_wireframe(false),
scissor_test(false),
depth_mask(true),
depth_func(DEPTH_NONE),
cull_face(CULL_BACK),
@ -41,8 +30,8 @@ struct BackendState {
current_vao(0),
current_program(nullptr) {}
int video_width;
int video_height;
bool debug_wireframe;
bool scissor_test;
bool depth_mask;
DepthFunc depth_func;
CullFace cull_face;
@ -53,37 +42,37 @@ struct BackendState {
ShaderProgram *current_program;
};
class GLBackend : public Backend {
class GLBackend : public Backend, public ui::WindowListener {
public:
GLBackend(sys::Window &window);
GLBackend(ui::Window &window);
~GLBackend();
int video_width() { return state_.video_width; }
int video_height() { return state_.video_height; }
bool Init();
void ResizeVideo(int width, int height);
bool Init() final;
TextureHandle RegisterTexture(PixelFormat format, FilterMode filter,
WrapMode wrap_u, WrapMode wrap_v,
bool gen_mipmaps, int width, int height,
const uint8_t *buffer);
void FreeTexture(TextureHandle handle);
const uint8_t *buffer) final;
void FreeTexture(TextureHandle handle) final;
void BeginFrame() final;
void EndFrame() final;
void Begin2D() final;
void End2D() final;
void BeginSurfaces2D(const Vertex2D *verts, int num_verts, uint16_t *indices,
int num_indices) final;
void DrawSurface2D(const Surface2D &surf) final;
void EndSurfaces2D() final;
void BeginFrame();
void RenderText2D(int x, int y, float point_size, uint32_t color,
const char *text);
void RenderBox2D(int x0, int y0, int x1, int y1, uint32_t color,
BoxType type);
void RenderLine2D(float *verts, int num_verts, uint32_t color);
void RenderSurfaces(const Eigen::Matrix4f &projection, const Surface *surfs,
int num_surfs, const Vertex *verts, int num_verts,
const int *sorted_surfs);
void EndFrame();
const int *sorted_surfs) final;
private:
void OnPaint(bool show_main_menu) final;
bool InitContext();
void DestroyContext();
@ -93,9 +82,9 @@ class GLBackend : public Backend {
void DestroyShaders();
void CreateVertexBuffers();
void DestroyVertexBuffers();
void DestroyFonts();
void SetupDefaultState();
void SetScissorTest(bool enabled);
void SetScissorClip(int x, int y, int width, int height);
void SetDepthMask(bool enabled);
void SetDepthFunc(DepthFunc fn);
void SetCullFace(CullFace fn);
@ -104,13 +93,8 @@ class GLBackend : public Backend {
void BindProgram(ShaderProgram *program);
void BindTexture(TextureMap map, GLuint tex);
GLint GetUniform(UniformAttr attr);
const BakedFont *GetFont(float point_size);
Eigen::Matrix4f Ortho2D();
Vertex2D *AllocVertices2D(const Surface2D &desc, int count);
void Flush2D();
sys::Window &window_;
ui::Window &window_;
SDL_GLContext ctx_;
BackendState state_;
GLuint textures_[MAX_TEXTURES];
@ -118,16 +102,10 @@ class GLBackend : public Backend {
ShaderProgram ta_program_;
ShaderProgram ui_program_;
GLuint ui_vao_, ui_vbo_;
GLuint ta_vao_, ta_vbo_;
Vertex2D verts2d_[MAX_2D_VERTICES];
int num_verts2d_;
Surface2D surfs2d_[MAX_2D_SURFACES];
int num_surfs2d_;
std::unordered_map<float, BakedFont *> fonts_;
GLuint ui_vao_, ui_vbo_, ui_ibo_;
bool ui_use_ibo_;
};
}
}

File diff suppressed because it is too large Load Diff

View File

@ -2,8 +2,8 @@ static const char *ui_vp = R"END(
uniform mat4 u_mvp;
layout(location = 0) in vec2 attr_xy;
layout(location = 1) in vec4 attr_color;
layout(location = 2) in vec2 attr_texcoord;
layout(location = 1) in vec2 attr_texcoord;
layout(location = 2) in vec4 attr_color;
out vec4 var_color;
out vec2 var_diffuse_texcoord;

View File

@ -1,74 +0,0 @@
#ifndef SYSTEM_H
#define SYSTEM_H
#include <SDL.h>
#include "core/ring_buffer.h"
#include "sys/keycode.h"
namespace re {
namespace sys {
enum {
MAX_EVENTS = 1024,
NUM_JOYSTICK_AXES = (K_AXIS15 - K_AXIS0) + 1,
NUM_JOYSTICK_KEYS = (K_JOY31 - K_JOY0) + 1,
};
enum WindowEventType {
WE_KEY,
WE_MOUSEMOVE,
WE_RESIZE,
WE_QUIT,
};
struct WindowEvent {
WindowEventType type;
union {
struct {
Keycode code;
int16_t value;
} key;
struct {
int x, y;
} mousemove;
struct {
int width;
int height;
} resize;
};
};
class Window {
public:
SDL_Window *handle() { return window_; }
int width() { return width_; }
int height() { return height_; }
Window();
~Window();
bool Init();
void PumpEvents();
bool PollEvent(WindowEvent *ev);
private:
void InitJoystick();
void DestroyJoystick();
void QueueEvent(const WindowEvent &ev);
Keycode TranslateSDLKey(const SDL_Keysym &keysym);
void PumpSDLEvents();
SDL_Window *window_;
int width_;
int height_;
SDL_Joystick *joystick_;
RingBuffer<WindowEvent> events_;
};
}
}
#endif

150
src/ui/imgui_impl.cc Normal file
View File

@ -0,0 +1,150 @@
#include "ui/imgui_impl.h"
#include "ui/window.h"
using namespace re;
using namespace re::renderer;
using namespace re::ui;
ImGuiImpl::ImGuiImpl(Window &window) : window_(window) {
window_.AddListener(this);
}
ImGuiImpl::~ImGuiImpl() {
window_.RemoveListener(this);
ImGui::Shutdown();
}
bool ImGuiImpl::Init() {
ImGuiIO &io = ImGui::GetIO();
Backend *rb = window_.render_backend();
// don't really care if this is accurate
io.DeltaTime = 1.0f / 60.0f;
// don't save settings
io.IniSavingRate = 0.0f;
// setup misc callbacks ImGui relies on
io.RenderDrawListsFn = nullptr;
io.SetClipboardTextFn = nullptr;
io.GetClipboardTextFn = nullptr;
// register front in backend
uint8_t *pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
TextureHandle handle =
rb->RegisterTexture(PXL_RGBA, FILTER_BILINEAR, WRAP_REPEAT, WRAP_REPEAT,
false, width, height, pixels);
io.Fonts->TexID = reinterpret_cast<void *>(static_cast<intptr_t>(handle));
return true;
}
void ImGuiImpl::OnPrePaint() {
ImGuiIO &io = ImGui::GetIO();
int width = window_.width();
int height = window_.height();
io.DisplaySize =
ImVec2(static_cast<float>(width), static_cast<float>(height));
ImGui::NewFrame();
}
void ImGuiImpl::OnPostPaint() {
ImGuiIO &io = ImGui::GetIO();
Backend *rb = window_.render_backend();
// if there are any focused items, enable text input
window_.EnableTextInput(ImGui::IsAnyItemActive());
// update draw batches. note, this doesn't _actually_ render anything because
// io.RenderDrawListsFn is null
ImGui::Render();
// get the latest draw batches, and pass them off out the render backend
ImDrawData *data = ImGui::GetDrawData();
rb->Begin2D();
for (int i = 0; i < data->CmdListsCount; ++i) {
const auto cmd_list = data->CmdLists[i];
Vertex2D *verts = reinterpret_cast<Vertex2D *>(cmd_list->VtxBuffer.Data);
int num_verts = cmd_list->VtxBuffer.size();
uint16_t *indices = cmd_list->IdxBuffer.Data;
int num_indices = cmd_list->IdxBuffer.size();
rb->BeginSurfaces2D(verts, num_verts, indices, num_indices);
int index_offset = 0;
for (int j = 0; j < cmd_list->CmdBuffer.size(); ++j) {
const auto &cmd = cmd_list->CmdBuffer[j];
Surface2D surf;
surf.prim_type = PRIM_TRIANGLES;
surf.texture =
static_cast<TextureHandle>(reinterpret_cast<intptr_t>(cmd.TextureId));
surf.src_blend = BLEND_SRC_ALPHA;
surf.dst_blend = BLEND_ONE_MINUS_SRC_ALPHA;
surf.scissor = true;
surf.scissor_rect[0] = cmd.ClipRect.x;
surf.scissor_rect[1] = io.DisplaySize.y - cmd.ClipRect.w;
surf.scissor_rect[2] = cmd.ClipRect.z - cmd.ClipRect.x;
surf.scissor_rect[3] = cmd.ClipRect.w - cmd.ClipRect.y;
surf.first_vert = index_offset;
surf.num_verts = cmd.ElemCount;
rb->DrawSurface2D(surf);
index_offset += cmd.ElemCount;
}
rb->EndSurfaces2D();
}
rb->End2D();
}
void ImGuiImpl::OnTextInput(const char *text) {
ImGuiIO &io = ImGui::GetIO();
io.AddInputCharactersUTF8(text);
}
void ImGuiImpl::OnKeyDown(Keycode code, int16_t value) {
ImGuiIO &io = ImGui::GetIO();
if (code == K_MWHEELUP) {
io.MouseWheel = value ? 1.0f : 0.0f;
} else if (code == K_MWHEELDOWN) {
io.MouseWheel = value ? -1.0f : 0.0f;
} else if (code == K_MOUSE1) {
io.MouseDown[0] = !!value;
} else if (code == K_MOUSE2) {
io.MouseDown[1] = !!value;
} else if (code == K_MOUSE3) {
io.MouseDown[2] = !!value;
} else if (code == K_LALT || code == K_RALT) {
alt_[code == K_LALT ? 0 : 1] = !!value;
io.KeyAlt = alt_[0] || alt_[1];
} else if (code == K_LCTRL || code == K_RCTRL) {
ctrl_[code == K_LCTRL ? 0 : 1] = !!value;
io.KeyCtrl = ctrl_[0] || ctrl_[1];
} else if (code == K_LSHIFT || code == K_RSHIFT) {
shift_[code == K_LSHIFT ? 0 : 1] = !!value;
io.KeyShift = shift_[0] || shift_[1];
}
}
void ImGuiImpl::OnMouseMove(int x, int y) {
ImGuiIO &io = ImGui::GetIO();
io.MousePos = ImVec2((float)x, (float)y);
}

34
src/ui/imgui_impl.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef IMGUI_IMPL_H
#define IMGUI_IMPL_H
#include <imgui.h>
#include "ui/window_listener.h"
namespace re {
namespace ui {
class Window;
class ImGuiImpl : public WindowListener {
public:
ImGuiImpl(Window &window);
~ImGuiImpl();
bool Init();
private:
void OnPrePaint() final;
void OnPostPaint() final;
void OnKeyDown(Keycode code, int16_t value) final;
void OnTextInput(const char *text) final;
void OnMouseMove(int x, int y) final;
Window &window_;
bool alt_[2];
bool ctrl_[2];
bool shift_[2];
};
}
}
#endif

View File

@ -1,8 +1,8 @@
#include "core/string.h"
#include "sys/keycode.h"
#include "ui/keycode.h"
namespace re {
namespace sys {
namespace ui {
struct Key {
Keycode code;

View File

@ -1,8 +1,8 @@
#ifndef KEYS_H
#define KEYS_H
#ifndef KEYCODE_H
#define KEYCODE_H
namespace re {
namespace sys {
namespace ui {
enum Keycode {
K_UNKNOWN,

1864
src/ui/microprofile_impl.cc Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,44 @@
#ifndef MICROPROFILE_IMPL_H
#define MICROPROFILE_IMPL_H
#include "renderer/backend.h"
#include "ui/window_listener.h"
namespace re {
namespace ui {
static const int MAX_2D_VERTICES = 16384;
static const int MAX_2D_SURFACES = 256;
class Window;
class MicroProfileImpl : public WindowListener {
public:
MicroProfileImpl(Window &window);
~MicroProfileImpl();
bool Init();
void DrawText(int x, int y, uint32_t color, const char *text);
void DrawBox(int x0, int y0, int x1, int y1, uint32_t color,
renderer::BoxType type);
void DrawLine(float *verts, int num_verts, uint32_t color);
private:
void OnPostPaint() final;
void OnKeyDown(Keycode code, int16_t value) final;
void OnMouseMove(int x, int y) final;
renderer::Vertex2D *AllocVertices(const renderer::Surface2D &desc, int count);
Window &window_;
renderer::TextureHandle font_tex_;
renderer::Surface2D surfs_[MAX_2D_SURFACES];
int num_surfs_;
renderer::Vertex2D verts_[MAX_2D_VERTICES];
int num_verts_;
};
}
}
#endif

View File

@ -1,51 +1,30 @@
#include <stdlib.h>
#include <SDL.h>
#include "sys/window.h"
#include "core/assert.h"
#include "renderer/gl_backend.h"
#include "ui/imgui_impl.h"
#include "ui/microprofile_impl.h"
#include "ui/window.h"
#define DEFAULT_WIDTH 800
#define DEFAULT_HEIGHT 600
using namespace re;
using namespace re::sys;
static inline WindowEvent MakeKeyEvent(Keycode code, int16_t value) {
WindowEvent ev;
ev.type = WE_KEY;
ev.key.code = code;
ev.key.value = value;
return ev;
}
static inline WindowEvent MakeMouseMoveEvent(int x, int y) {
WindowEvent ev;
ev.type = WE_MOUSEMOVE;
ev.mousemove.x = x;
ev.mousemove.y = y;
return ev;
}
static inline WindowEvent MakeResizeEvent(int width, int height) {
WindowEvent ev;
ev.type = WE_RESIZE;
ev.resize.width = width;
ev.resize.height = height;
return ev;
}
static inline WindowEvent MakeQuitEvent() {
WindowEvent ev;
ev.type = WE_QUIT;
return ev;
}
using namespace re::renderer;
using namespace re::ui;
Window::Window()
: window_(nullptr),
rb_(nullptr),
imgui_(*this),
microprofile_(*this),
width_(DEFAULT_WIDTH),
height_(DEFAULT_HEIGHT),
joystick_(nullptr),
events_(MAX_EVENTS) {}
joystick_(nullptr) {}
Window::~Window() {
delete rb_;
DestroyJoystick();
if (window_) {
@ -62,6 +41,7 @@ bool Window::Init() {
return false;
}
// setup native window
window_ = SDL_CreateWindow("redream", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, width_, height_,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
@ -70,22 +50,64 @@ bool Window::Init() {
return false;
}
return true;
}
// setup render context
rb_ = new GLBackend(*this);
void Window::PumpEvents() { PumpSDLEvents(); }
bool Window::PollEvent(WindowEvent *ev) {
if (events_.Empty()) {
if (!rb_->Init()) {
LOG_WARNING("Render context creation failed");
return false;
}
*ev = events_.front();
events_.PopFront();
// setup imgui
if (!imgui_.Init()) {
LOG_WARNING("ImGui initialization failed");
return false;
}
// setup microprofile
if (!microprofile_.Init()) {
LOG_WARNING("MicroProfile initialization failed");
return false;
}
return true;
}
void Window::AddListener(WindowListener *listener) {
listeners_.push_back(listener);
}
void Window::RemoveListener(WindowListener *listener) {
auto it = std::find(listeners_.begin(), listeners_.end(), listener);
if (it == listeners_.end()) {
return;
}
listeners_.erase(it);
}
bool Window::MainMenuEnabled() { return show_main_menu_; }
void Window::EnableMainMenu(bool active) { show_main_menu_ = active; }
bool Window::TextInputEnabled() { return SDL_IsTextInputActive(); }
void Window::EnableTextInput(bool active) {
if (active) {
SDL_StartTextInput();
} else {
SDL_StopTextInput();
}
}
void Window::PumpEvents() {
PumpSDLEvents();
// trigger a paint event after draining all other window-related events
HandlePaint();
}
void Window::InitJoystick() {
DestroyJoystick();
@ -107,13 +129,46 @@ void Window::DestroyJoystick() {
}
}
void Window::QueueEvent(const WindowEvent &ev) {
if (events_.Full()) {
LOG_WARNING("System event overflow");
return;
void Window::HandlePaint() {
rb_->BeginFrame();
for (auto listener : listeners_) {
listener->OnPrePaint();
}
events_.PushBack(ev);
for (auto listener : listeners_) {
listener->OnPaint(show_main_menu_);
}
for (auto listener : listeners_) {
listener->OnPostPaint();
}
rb_->EndFrame();
}
void Window::HandleKeyDown(Keycode code, int16_t value) {
for (auto listener : listeners_) {
listener->OnKeyDown(code, value);
}
}
void Window::HandleTextInput(const char *text) {
for (auto listener : listeners_) {
listener->OnTextInput(text);
}
}
void Window::HandleMouseMove(int x, int y) {
for (auto listener : listeners_) {
listener->OnMouseMove(x, y);
}
}
void Window::HandleClose() {
for (auto listener : listeners_) {
listener->OnClose();
}
}
Keycode Window::TranslateSDLKey(const SDL_Keysym &keysym) {
@ -653,7 +708,7 @@ void Window::PumpSDLEvents() {
Keycode keycode = TranslateSDLKey(ev.key.keysym);
if (keycode != K_UNKNOWN) {
QueueEvent(MakeKeyEvent(keycode, 1));
HandleKeyDown(keycode, 1);
}
} break;
@ -661,10 +716,14 @@ void Window::PumpSDLEvents() {
Keycode keycode = TranslateSDLKey(ev.key.keysym);
if (keycode != K_UNKNOWN) {
QueueEvent(MakeKeyEvent(keycode, 0));
HandleKeyDown(keycode, 0);
}
} break;
case SDL_TEXTINPUT: {
HandleTextInput(ev.text.text);
} break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP: {
Keycode keycode;
@ -691,23 +750,22 @@ void Window::PumpSDLEvents() {
}
if (keycode != K_UNKNOWN) {
QueueEvent(
MakeKeyEvent(keycode, ev.type == SDL_MOUSEBUTTONDOWN ? 1 : 0));
HandleKeyDown(keycode, ev.type == SDL_MOUSEBUTTONDOWN ? 1 : 0);
}
} break;
case SDL_MOUSEWHEEL:
if (ev.wheel.y > 0) {
QueueEvent(MakeKeyEvent(K_MWHEELUP, 1));
QueueEvent(MakeKeyEvent(K_MWHEELUP, 0));
HandleKeyDown(K_MWHEELUP, 1);
HandleKeyDown(K_MWHEELUP, 0);
} else {
QueueEvent(MakeKeyEvent(K_MWHEELDOWN, 1));
QueueEvent(MakeKeyEvent(K_MWHEELDOWN, 0));
HandleKeyDown(K_MWHEELDOWN, 1);
HandleKeyDown(K_MWHEELDOWN, 0);
}
break;
case SDL_MOUSEMOTION:
QueueEvent(MakeMouseMoveEvent(ev.motion.x, ev.motion.y));
HandleMouseMove(ev.motion.x, ev.motion.y);
break;
case SDL_JOYDEVICEADDED:
@ -717,16 +775,15 @@ void Window::PumpSDLEvents() {
case SDL_JOYAXISMOTION:
if (ev.jaxis.axis < NUM_JOYSTICK_AXES) {
QueueEvent(
MakeKeyEvent((Keycode)(K_AXIS0 + ev.jaxis.axis), ev.jaxis.value));
HandleKeyDown((Keycode)(K_AXIS0 + ev.jaxis.axis), ev.jaxis.value);
}
break;
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP:
if (ev.jbutton.button < NUM_JOYSTICK_KEYS) {
QueueEvent(MakeKeyEvent((Keycode)(K_JOY1 + ev.jbutton.button),
ev.type == SDL_JOYBUTTONDOWN ? 1 : 0));
HandleKeyDown((Keycode)(K_JOY1 + ev.jbutton.button),
ev.type == SDL_JOYBUTTONDOWN ? 1 : 0);
}
break;
@ -735,14 +792,12 @@ void Window::PumpSDLEvents() {
case SDL_WINDOWEVENT_RESIZED: {
width_ = ev.window.data1;
height_ = ev.window.data2;
QueueEvent(MakeResizeEvent(width_, height_));
} break;
}
break;
case SDL_QUIT:
QueueEvent(MakeQuitEvent());
HandleClose();
break;
}
}

71
src/ui/window.h Normal file
View File

@ -0,0 +1,71 @@
#ifndef SYSTEM_H
#define SYSTEM_H
#include <vector>
#include <SDL.h>
#include "renderer/backend.h"
#include "ui/keycode.h"
#include "ui/imgui_impl.h"
#include "ui/microprofile_impl.h"
#include "ui/window_listener.h"
namespace re {
namespace ui {
enum {
NUM_JOYSTICK_AXES = (K_AXIS15 - K_AXIS0) + 1,
NUM_JOYSTICK_KEYS = (K_JOY31 - K_JOY0) + 1,
};
class Window {
public:
SDL_Window *handle() { return window_; }
renderer::Backend *render_backend() { return rb_; }
int width() { return width_; }
int height() { return height_; }
Window();
~Window();
bool Init();
void AddListener(WindowListener *listener);
void RemoveListener(WindowListener *listener);
bool MainMenuEnabled();
void EnableMainMenu(bool active);
bool TextInputEnabled();
void EnableTextInput(bool active);
void PumpEvents();
private:
void HandlePaint();
void HandleKeyDown(Keycode code, int16_t value);
void HandleTextInput(const char *text);
void HandleMouseMove(int x, int y);
void HandleResize(int width, int height);
void HandleClose();
void InitJoystick();
void DestroyJoystick();
Keycode TranslateSDLKey(const SDL_Keysym &keysym);
void PumpSDLEvents();
std::vector<WindowListener *> listeners_;
SDL_Window *window_;
renderer::Backend *rb_;
ImGuiImpl imgui_;
MicroProfileImpl microprofile_;
int width_;
int height_;
bool show_main_menu_;
SDL_Joystick *joystick_;
};
}
}
#endif

23
src/ui/window_listener.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef WINDOW_LISTENER_H
#define WINDOW_LISTENER_H
#include <stdint.h>
#include "ui/keycode.h"
namespace re {
namespace ui {
class WindowListener {
public:
virtual void OnPrePaint(){};
virtual void OnPaint(bool show_main_menu){};
virtual void OnPostPaint(){};
virtual void OnKeyDown(Keycode code, int16_t value){};
virtual void OnTextInput(const char *text) {}
virtual void OnMouseMove(int x, int y){};
virtual void OnClose(){};
};
}
}
#endif

View File

@ -1,98 +0,0 @@
#include <gtest/gtest.h>
#include "core/ring_buffer.h"
using namespace re;
class RingTest : public ::testing::Test {
public:
RingTest() : items(2) {}
RingBuffer<int> items;
};
// empty / full
TEST_F(RingTest, Size) {
ASSERT_TRUE(items.Empty());
items.PushBack(7);
ASSERT_TRUE(!items.Empty() && !items.Full());
items.PushBack(9);
ASSERT_TRUE(items.Full());
items.PopBack();
ASSERT_TRUE(!items.Full());
items.PopFront();
ASSERT_TRUE(items.Empty());
}
// add tests
TEST_F(RingTest, PushBack) {
// push the first two items and fill up the buffer
items.PushBack(7);
items.PushBack(9);
ASSERT_EQ(7, items.front());
ASSERT_EQ(7, *items.begin());
ASSERT_EQ(9, items.back());
ASSERT_EQ(9, *(--items.end()));
ASSERT_EQ(2, (int)items.Size());
// push two more to overwrite
items.PushBack(10);
items.PushBack(11);
ASSERT_EQ(10, items.front());
ASSERT_EQ(10, *items.begin());
ASSERT_EQ(11, items.back());
ASSERT_EQ(11, *(--items.end()));
ASSERT_EQ(2, (int)items.Size());
}
// remove tests
TEST_F(RingTest, PopBack) {
items.PushBack(7);
items.PushBack(9);
ASSERT_EQ(9, *(--items.end()));
ASSERT_EQ(2, (int)items.Size());
items.PopBack();
ASSERT_EQ(7, items.front());
ASSERT_EQ(7, *items.begin());
ASSERT_EQ(7, items.back());
ASSERT_EQ(7, *(--items.end()));
ASSERT_EQ(1, (int)items.Size());
}
TEST_F(RingTest, PopFront) {
items.PushBack(7);
items.PushBack(9);
ASSERT_EQ(9, *(--items.end()));
ASSERT_EQ(2, (int)items.Size());
items.PopFront();
ASSERT_EQ(9, items.front());
ASSERT_EQ(9, *items.begin());
ASSERT_EQ(9, items.back());
ASSERT_EQ(9, *(--items.end()));
ASSERT_EQ(1, (int)items.Size());
}
TEST_F(RingTest, Clear) {
items.PushBack(7);
items.PushBack(9);
ASSERT_EQ(2, (int)items.Size());
items.Clear();
ASSERT_EQ(0, (int)items.Size());
}
// iterator tests
TEST_F(RingTest, EmptyIterate) { ASSERT_EQ(items.begin(), items.end()); }
TEST_F(RingTest, ForwardIterator) {
items.PushBack(7);
items.PushBack(9);
auto it = items.begin();
ASSERT_EQ(7, *it);
ASSERT_EQ(9, *(++it));
ASSERT_EQ(items.end(), ++it);
}

View File

@ -102,7 +102,7 @@ int sh4_num_test_regs =
xf12, xf13, xf14, xf15) \
SH4Context { \
nullptr, nullptr, nullptr, nullptr, nullptr, \
0, \
0, 0, \
0, 0, 0, 0, fpscr, \
0, 0, 0, \
0, 0, 0, \